﻿var msgindex = 0, PointTypePlanHasMaxValueDictionary = new Array(), DevicePointStatus = [], maploadinged = false;

function GetPointTypeAnalysisConfig(id) {
    var datas = $("#pointtypeconfig").data("info");
    for (var i = 0; i < datas.length; i++) {
        if (datas[i].TypeId === id)
            return datas[i];
    }
}
//去除字符串头尾空格或指定字符
String.prototype.Trim = function (c) {
    if (c == null || c == "") {
        var str = this.replace(/^s*/, '');
        var rg = /s/;
        var i = str.length;
        while (rg.test(str.charAt(--i)));
        return str.slice(0, i + 1);
    }
    else {
        var rg = new RegExp("^" + c + "*");
        var str = this.replace(rg, '');
        rg = new RegExp(c);
        var i = str.length;
        while (rg.test(str.charAt(--i)));
        return str.slice(0, i + 1);
    }
}
//去除字符串头部空格或指定字符  
String.prototype.TrimStart = function (c) {
    if (c == null || c == "") {
        var str = this.replace(/^s*/, '');
        return str;
    }
    else {
        var rg = new RegExp("^" + c + "*");
        var str = this.replace(rg, '');
        return str;
    }
}

//去除字符串尾部空格或指定字符  
String.prototype.trimEnd = function (c) {
    if (c == null || c == "") {
        var str = this;
        var rg = /s/;
        var i = str.length;
        while (rg.test(str.charAt(--i)));
        return str.slice(0, i + 1);
    }
    else {
        var str = this;
        var rg = new RegExp(c);
        var i = str.length;
        while (rg.test(str.charAt(--i)));
        return str.slice(0, i + 1);
    }
}
if (PointTypePlanHasMaxValueDictionary.length == 0) {
    $.post("/Setting/GetPointTypePlanHasMaxValueDictionary", {}, function (result) {
        PointTypePlanHasMaxValueDictionary = $.parseJSON(result);
    });
}

if (typeof PointStatus == "undefined") {
    var PointStatus = {};
    PointStatus.Red = 2;
    PointStatus.Yellow = 5;
    PointStatus.Green = 0;
    PointStatus.Hardware = 3;
    PointStatus.Orange = 1;
    PointStatus.Blue = 4;
}

/*** 设备状态颜色等级排序 */
var PointStatusRankEnum = {
    Green: 0,
    Grey: 1,
    Blue: 2,
    Yellow: 3,
    Orange: 4,
    Red: 5
}

function loaddinghide() {
    layer.close(msgindex);
    $(".modal-backdrop").hide();
    $(".layui-layer-move").hide();
}

function loaddingshow() {
    msgindex = layer.load(1, {
        shade: [0.1, '#fff'] //0.1透明度的白色背景
    });
    $(".modal-backdrop").show();
    $(".layui-layer-move").show();
}

//传感器类型枚举值
var PointTypeEnum = {
    NaoDu: 1,//挠度
    WenDu: 2,//温度
    ShiDu: 3,//湿度
    ShenSuoFengWeiYi: 4,//伸缩缝位移
    ChuanZhuang: 5,//船撞
    TaPianWeiYi: 6,//塔偏位移
    FengSuFengXiang: 7,//风速风向
    ZhenDong: 8,//振动
    CheLiuLiang: 9,//车流量
    SuoLi: 10,//索力
    KongJianGps: 11,//空间GPS
    PianYiWeiYi: 12,//偏移位移
    YingBian: 13,//应变
    Gnss: 14,//GNSS
    FengSu: 15,//风速
    FengXiang: 16,//风向
    ZhongChe: 17,//重车
    QingJiao: 18,//倾角
    YeWei: 19,//液位
    LieFeng: 20,//裂缝
    SuoLiJiaSuDu: 21,//索力加速度
    TuYaLi: 22,//土压力
    ShuiWei: 23,//水位
    JiangYuLiang: 24,//降雨量
    ShenBuWeiYi: 25,//深部位移
    GaoChengWeiYi: 26,//高程位移
    ShuiPingWeiYi: 27,//水平位移
    ShenLiu: 28,//渗流
    JiaWan: 29,//甲烷
    JianKongLiangCe: 30,//监控梁测
    Led: 31,//LED
    VideoImage: 32,//视频图片
    Video: 33,//视频
    JinRunXian: 34,//浸润线
    ZhiZuoWeiYi: 35//支座位移
};
Date.prototype.format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

Date.prototype.addDays = function (date, days) {
    date.setMilliseconds(date.getMilliseconds() + (days * 24 * 60 * 60 * 1000));
    return date;
}
Date.prototype.addHours = function (date, hour) {
    date.setMilliseconds(date.getMilliseconds() + (hour * 60 * 60 * 1000));
    return date;
}
function contains(arr, obj) {
    if (arr == undefined) {
        return false;
    }
    var i = arr.length;
    while (i--) {
        if (arr[i] === obj) {
            return true;
        }
    }
    return false;
}

function indexOf(str, key) {
    return str.indexOf(key);
}
function ValidateNum(value) {
    var reg = new RegExp("^[0-9]*$");
    if (!reg.test(value)) {
        return false;
    }
    if (!/^[0-9]+$/.test(value)) {
        return false;
    }
    return true;
}
function CloseIframeUploadWindow(layerid) {
    layer.close(layerid);
}
//自定义字典对象
function Dictionary() {
    this.data = new Array();

    this.put = function (key, value) {
        this.data[key] = value;
    };

    this.get = function (key) {
        return this.data[key];
    };

    this.remove = function (key) {
        this.data[key] = null;
    };

    this.isEmpty = function () {
        return this.data.length == 0;
    };

    this.size = function () {
        return this.data.length;
    };
}

function ShowWarningDetail(id) {
    LoadWarningDetailData(id);
}

function LoadWarningDetailData(id) {
    showDragDialog('Model_WarningDetailInfoWindow');
    loaddingshow();
    $("#Model_WarningDetailInfoWindow .modal-content").empty();
    $.get($("#AnalysisWarningAddress").val().trimEnd('/') + "/view/analysis/warning/detail/monitorobjectid/" + $("#BridgeId").val() + "/warningid/" + id, function (result) {
        loaddinghide();
        $("#Model_WarningDetailInfoWindow .modal-content").html(result);
        $("#Model_WarningDetailInfoWindow .modal-header .icon-close").click(function () {
            hideDragDialog();
        });
        $("#Model_WarningDetailInfoWindow").data("warningid", id);
        setTimeout(function () {
            $("#Model_WarningDetailInfoWindow .modal-content .handlerinfodiv").html($("#Model_WarningDetailInfoHandlerWindow").html());//附加预警处理内容
            $("#Model_WarningDetailInfoWindow .modal-content .handlebtn").click(function () {
                processWarning(this);
            });//绑定处理事件
            $("#Model_WarningDetailInfoWindow .modal-content .warninghandlerinput #HandleType").change(function () {
                if ($(this).val() == 1) {//通知人员
                    $(this).parent().find("#manual_user_pannel").show();
                    $(this).parent().find(".soundlightset").hide();
                } else if ($(this).val() == 2) {//声光报警器
                    $(this).parent().find("#manual_user_pannel").hide();
                    $(this).parent().find(".soundlightset").css("display", "inline-block");
                } else {//忽略
                    $(this).parent().find("#manual_user_pannel").hide();
                    $(this).parent().find(".soundlightset").hide();
                }
            });//绑定选择处理类型select事件
            $("#Model_WarningDetailInfoWindow .modal-content .savewarningbtn").click(function () {
                ShowWanringHandle(this);
            });//绑定保存事件
        }, 500);
    });
}
function ClearMonitorSettingData() {
    $.post("/Setting/ClearMonitorSettingData", { monitorobjectid: $("#BridgeId").val() }, function () {

    });
}

function processWarning(obj) {
    $("#HandleType").val(0);
    $("#manual_user_pannel").hide();

    $("#manual_add_msg_users").empty();
    $.post($("#DataApiAddress").val() + 'api/msgconfig/GetAllUser?deptid=' + $("#current_userDeptid").val(), function (datas) {
        if (datas.Code == 200) {
            var data = datas.Result;
            var userhtml = "";
            for (var i = 0; i < data.length; i++) {
                userhtml += '<li role="presentation" class="addPeopleitem">'
                    + '<input type = "checkbox" name = "" value = "' + data[i].USER_INFO_ID + '" >'
                    + '<span class="checkboxStyle"></span> '
                    + '<span class="peopleName">' + data[i].USER_INFO_NICKNAME + '(' + data[i].DeptName + ')' + '</span>'
                    + '</li >';
            }
            $("#Model_WarningDetailInfoWindow .modal-content #manual_add_msg_users").html(userhtml);
            $("#Model_WarningDetailInfoWindow .modal-content #manual_add_msg_users").show();
        }
    });

    $(obj).hide();
    $("#Model_WarningDetailInfoWindow .modal-content .handlerinfodiv").show();
    $('.warninghandler').show();
    $("#Model_WarningDetailInfoWindow").parent().scrollTop(999);
}
//正整数
function checkInt(e) {
    var re = new RegExp("^[0-9]*[1-9][0-9]*$");
    return re.test(e);
}
function ShowWanringHandle(obj) {
    if ($.trim($("#Model_WarningDetailInfoWindow .modal-content #HandleType").val()) == "") {
        layer.alert("处理情况不能为空", { title: "保存提示" });
        return;
    }
    if (($.trim($("#Model_WarningDetailInfoWindow .modal-content #HandleType").val()) * 1) == 2 && !checkInt($("#Model_WarningDetailInfoWindow .modal-content #soundligntmiute").val())) {
        layer.alert("声光报警器报警秒数输入错误", { title: "保存提示" });
        return;
    }
    var userids = new Array();
    var cklist = $('#manual_add_msg_users input[type="checkbox"]');
    cklist.each(function () {
        if ($(this).is(':checked')) {
            userids.push($(this).val());
        }
    });
    $(obj).attr("disabled", "disabled");
    var id = $("#Model_WarningDetailInfoWindow").data("warningid");
    var url = $("#DataApiAddress").val() + "api/warning/HandlerWarning/" + $("#BridgeId").val() + "/" + id + "?soundminute=" + $("#Model_WarningDetailInfoWindow .modal-content #soundligntmiute").val();
    $.post(url, { reason: $.trim($("#Model_WarningDetailInfoWindow .modal-content #WarningReason").val()), handlertype: $("#Model_WarningDetailInfoWindow .modal-content #HandleType").val(), userids: userids },
        function (data) {
            $(obj).removeAttr("disabled");
            if (data.Code === 200) {
                layer.msg("预警已成功处理");
                $(obj).parents(".modal-content").find("button.close").click();

                if ($(".warningnotice .warningnum").length > 0) {//处理首页顶部 预警数量及列表
                    var num = $(".warningnotice .warningnum").text() * 1;
                    $(".warningnotice .warningnum").text(num > 0 ? num - 1 : 0);
                    $(".warningnotice .noticeMsg .warnging_" + id).remove();
                }
                if ($(".warningstasticsrefrash").length > 0) {
                    $(".warningstasticsrefrash").click();
                }

                hideDragDialog();
            } else {
                layer.alert("报警处理信息失败", { title: "保存提示" });
            }
        }
    );
}

function InstallationLeftMenus() {
    var menuscookiekey = 'slope_menusdata_' + $("#BridgeId").val() + "_" + $("#RoleId").val();
    var nowbridgemenuscookies = $.cookie(menuscookiekey);
    if (nowbridgemenuscookies == "" || nowbridgemenuscookies == undefined || nowbridgemenuscookies === "null") {
        $.get($("#DataApiAddress").val() + "/webapi/web/getmenus/" + $("#BridgeId").val() + "/" + $("#RoleId").val(), {}, function (result) {
            if (result.Code === 200) {
                var menudata = [];
                for (var i = 0; i < result.Result.length; i++) {
                    var n = new Object();
                    n.I = result.Result[i].FUNCTION_Id;
                    n.N = result.Result[i].FUNCTION_NAME;
                    n.A = result.Result[i].FUNCTION_ACTION;
                    menudata.push(n);
                }

                $.cookie(menuscookiekey, JSON.stringify(menudata), { expires: 0.1, path: '/' });
                LoadMenus(menudata);
            } else {
                console.log("绑定菜单时发生错误：" + result.Message);
            }
        });
    } else {
        LoadMenus($.parseJSON(nowbridgemenuscookies));
    }
}
function LoadMenus(menusdata) {
    var menuhtmls = "";
    for (var i = 0; i < menusdata.length; i++) {
        if (menusdata[i].I !== 6) {
            menuhtmls += '<li class="sideBar_drag dropdown" id="menu_' + menusdata[i].I + '"><a href="' + menusdata[i].A + '/' + $("#BridgeId").val() + '"><i class="ico ico-sideBar-' + menusdata[i].I + '"></i><span>' + menusdata[i].N + '</span></a></li>';
        }
    }
    $("#menuul").html(menuhtmls);
    $("#menu_" + $("#NowFeatureId").val()).addClass("active");
}

function setChartInfo(pointtypecn) {
    switch (pointtypecn) {
        case "挠度":
            chatYTitle = "挠度：mm";
            dataUnit = "mm";
            break;
        case "车流量":
            chatYTitle = "车流量：辆";
            dataUnit = "辆";
            break;
        case "重车":
            chatYTitle = "重车：辆";
            dataUnit = "辆";
            break;
        case "应变":
            chatYTitle = "应变：uε（微应变）";
            dataUnit = "uε";
            break;
        case "索力":
            chatYTitle = "索力：KN（千牛）";
            dataUnit = "KN";
            break;
        case "索力加速度":
            chatYTitle = "索力加速度：mg";
            dataUnit = "mg";
            break;
        case "风速风向":
            chatYTitle = "风速风向：M/S(米/秒)";
            dataUnit = "M/S";
            break;
        case "塔偏位移":
            chatYTitle = "主塔偏移：°（度）";
            dataUnit = "°";
            break;
        case "伸缩缝位移":
            chatYTitle = "伸缩缝位移：mm";
            dataUnit = "mm";
            break;
        case "偏移位移":
            chatYTitle = "偏移位移：mm";
            dataUnit = "mm";
            break;
        case "GNSS":
            chatYTitle = "GNSS：mm";
            dataUnit = "mm";
            break;
        case "温度":
            chatYTitle = "温度：°C";
            dataUnit = "°C";
            break;
        case "湿度":
            chatYTitle = "湿度：%RH";
            dataUnit = "%RH";
            break;
        case "振动":
            chatYTitle = "振动：mg";
            dataUnit = "mg";
            break;
        case "车辆荷载":
            chatYTitle = "车流量：辆";
            dataUnit = "辆";
            break;
        case "倾角":
            chatYTitle = "倾角：mm";
            dataUnit = "mm";
            break;
        case "空间GPS":
            chatYTitle = "空间GPS:m";
            dataUnit = "m";
            break;
        case "液位":
            chatYTitle = "液位：mm";
            dataUnit = "mm";
            break;
        case "裂缝":
            chatYTitle = "裂缝：mm";
            dataUnit = "mm";
            break;
        case "表面位移":
            chatYTitle = "表面位移：mm";
            dataUnit = "mm";
            break;
        case "深部位移":
            chatYTitle = "深部位移：mm";
            dataUnit = "mm";
            break;
        case "土压力":
            chatYTitle = "土压力：KPa";
            dataUnit = "KPa";
            break;
        case "渗流":
            chatYTitle = "渗流：MPa";
            dataUnit = "MPa";
            break;
        case "降雨量":
            chatYTitle = "降雨量：mm";
            dataUnit = "mm";
            break;
        case "水位":
            chatYTitle = "相对水位：mm";
            dataUnit = "mm";
            break;
        case "相对水位":
            chatYTitle = "相对水位：mm";
            dataUnit = "mm";
            break;
        case "浸润线":
            chatYTitle = "浸润线：m";
            dataUnit = "m";
            break;
        case "支座位移":
            chatYTitle = "支座位移：mm";
            dataUnit = "mm";
            break;
        case "图像位移":
            chatYTitle = "图像位移：mm";
            dataUnit = "mm";
            break;
        default:
            chatYTitle = "";
            dataUnit = "";
            break;
    }
    var re = new Array();
    re.push(chatYTitle);
    re.push(dataUnit);
    return re;
}
function InstallationRoleSettingMenus() {
    var rolesettingmenuscookiekey = 'slope_rolesettingmenusdata_' + $("#BridgeId").val() + "_" + $("#RoleId").val();
    var rolesettingmenuscookies = $.cookie(rolesettingmenuscookiekey);
    if (rolesettingmenuscookies === "" || rolesettingmenuscookies == undefined || rolesettingmenuscookies === "[]") {
        $.get($("#DataApiAddress").val() + "/webapi/web/getsettingmenus/" + $("#BridgeId").val() + "/" + $("#RoleId").val(), {}, function (result) {
            if (result.Code === 200) {
                var rolesetmenus = [];
                for (var i = 0; i < result.Result.length; i++) {
                    var n = new Object();
                    n.I = result.Result[i].FUNCTION_Id;
                    n.N = result.Result[i].FUNCTION_NAME;
                    n.A = result.Result[i].FUNCTION_ACTION;
                    rolesetmenus.push(n);
                }

                $.cookie(rolesettingmenuscookiekey, JSON.stringify(rolesetmenus), { expires: 0.1, path: '/' });
                LoadRoleSettingMenus(rolesetmenus);
            } else {
                console.log("绑定设置权限菜单时发生错误：" + result.Message);
            }
        });
    } else {
        LoadRoleSettingMenus($.parseJSON(rolesettingmenuscookies));
    }
}

var warningInterval;
function InstallationLayoutWarningInfo() {
    if (warningInterval != undefined && warningInterval != null) {
        window.clearTimeout(warningInterval);
    }
    LoadLayoutWarningInfo();
    warningInterval = setInterval('LoadLayoutWarningInfo()', 60000);//21分钟(60000)请求一次
}
/** 加载预警信息 */
function LoadLayoutWarningInfo() {
    $(".warningnotice .warningnum").html("<img src='/content/img/loading.gif'/>");
    $.get($("#DataApiAddress").val() + "/warning/getwarninglist/" + $("#BridgeId").val() + "/null/null/0/null/0/null", {}, function (result) {
        if (result.Code == 200) {
            var newLoadingStatus = 0;
            var resultData = result.Result;
            var hardwareCount = 0;
            //各预警级别展示开关
            var isRed = false, isOrange = false, isYellow = false, isBlue = false;
            var listdata = resultData.DataList;
            var htmls = "";
            var warningwindowhtmls = "";
            var pointstatu = PointStatus.Green;
            var pointStatusRank = PointStatusRankEnum.Green;
            var rightTypeUls = $("#monitorPoint .addpointtypepanel");
            for (var i = 0; i < listdata.length; i++) {
                var nclassname = "";//红,橙,黄，蓝 一般预警,硬件异常
                if (listdata[i].WarningType === 2) {
                    nclassname = "serious";//红
                    pointstatu = PointStatus.Red;
                    pointStatusRank = PointStatusRankEnum.Red;
                    if (!isRed) {
                        isRed = true;
                    }
                } else if (listdata[i].WarningType === 1) {
                    nclassname = "general";//橙
                    pointStatusRank = PointStatusRankEnum.Orange;
                    pointstatu = PointStatus.Orange;
                    if (!isOrange) {
                        isOrange = true;
                    }
                } else if (listdata[i].WarningType === 5) {
                    nclassname = "yellow";//黄
                    pointStatusRank = PointStatusRankEnum.Yellow;
                    pointstatu = PointStatus.Yellow;
                    if (!isYellow) {
                        isYellow = true;
                    }
                }  else if (listdata[i].WarningType === 4) {
                    nclassname = "blue";//蓝色
                    pointstatu = PointStatus.Blue;
                    pointStatusRank = PointStatusRankEnum.Blue;
                    if (!isBlue) {
                        isBlue = true;
                    }
                } else if (listdata[i].WarningType === 3) {
                    hardwareCount++;
                    nclassname = "abnormal";//灰色
                    $("input.menu_sec_name[value*='" + listdata[i].PointName + "']").parent().find(".state").removeClass("pointstatus_");
                    pointstatu = $("input.menu_sec_name[value*='" + listdata[i].PointName + "']").parent().find(".state").data("pointstatus");
                }
                if ($(".warnging_" + listdata[i].Id).length === 0) {
                    var baseerrorinfo = listdata[i].WarningMessage.split(',')[1];
                    baseerrorinfo = baseerrorinfo == undefined ? "" : baseerrorinfo;
                    htmls += "<li class='warnging_" + listdata[i].Id + " warnging_" + listdata[i].PointName + "_" + pointstatu + " " + nclassname + "' onclick='ShowWarningDetail(" + listdata[i].Id + ")' " +
                        "title='" + listdata[i].WarningMessage + "'>" +
                        "<span class='tit'>" + listdata[i].SupportSugistion + " " + listdata[i].PointShowText + "</span><span class='msg'>" + listdata[i].DateTime.replace("T", " ") + baseerrorinfo + "</span></li>";
                }
                warningwindowhtmls +=
                    '<div class="item ' + (i === 0 ? "active" : "") + '" index="' + (i + 1) + '" data-pointname="' + listdata[i].PointName + '" data-pointtypename="' + listdata[i].Type + '">' +
                    '<section class="warning-caption clearfix">' +
                    '<span class="warning-leve ' + nclassname + '"></span>' +
                    '<span class="warning-title">' + listdata[i].Type + '</span>' +
                    '<span class="warning-title">' + listdata[i].SupportSugistion + '</span>' +
                    '<time>' + listdata[i].DateTime.replace("T", " ") + '</time>' +
                    '<a href="javascript:void(0)" onclick="ShowWarningDetail(' + listdata[i].Id + ')">详情</a>' +
                    '</section>' +
                    '<div class="warning-coantent">' +
                    '<p>' + listdata[i].WarningMessage + '</p>' +
                    '</div>' +
                    '</div>';

                //设置传感器状态
                var pointStatusRankSrc = $("#set_pointli_" + listdata[i].PointId + " .state").data("pointstatusrank");
                if (pointStatusRankSrc == undefined || pointStatusRank > pointStatusRankSrc) {
                    $("#set_pointli_" + listdata[i].PointId + " .state").removeClass("pointstatus_0").removeClass("pointstatus_1").removeClass("pointstatus_2").removeClass("pointstatus_3").removeClass("pointstatus_4").removeClass("pointstatus_5").addClass("pointstatus_" + pointstatu);
                    $("#set_pointli_" + listdata[i].PointId + " .state").data("pointstatus", pointstatu);
                    $("#set_pointli_" + listdata[i].PointId + " .state").data("pointstatusrank", pointStatusRank);
                }
            };
            var $slider = '<div id="warningBar-slider" class="carousel slide warningBar-slider"><section class="warning-top clearfix"><a class="pull-right icon icon-close" href = "javascript:;" ></a ><h5 class="pull-left">预警信息</h5><div class="warning-indicators"><a class="icon icon-left" href="#warningBar-slider" role="button" data-slide="prev"></a><span class="warn-indicator">1&nbsp;/&nbsp;' + resultData.AllCount + '</span><a class="icon icon-right" href="#warningBar-slider" role="button" data-slide="next"></a></div></section ><div class="carousel-inner" role="listbox">' + warningwindowhtmls + '</div></div > ';
            $(".warningnotice .warningnum").text(resultData.AllCount);

            $("#warninginfowindow").html($slider);
            $(".warningcount").text(resultData.AllCount - hardwareCount);
            $('.warningBar-slider').carousel({
                interval: 0
            }).on('slide.bs.carousel',
                function (event) {
                    var carouselData = $(this).data('bs.carousel');
                    var items = carouselData.$items.length; //所有图片的包裹div的数组
                    setTimeout(function () {
                        var $index = $(".warningBar-slider .item.active").attr("index");
                        $(".warn-indicator").html($index + "&nbsp;/&nbsp;" + items);
                        LoadMapModelShowPointFromWarningWindow();
                    },
                        800);
                });

            $(".warning-top").on('click', ".icon-close", function (e) {
                e.stopPropagation();
                $('.warningBar').hide();
            });
            if (resultData.AllCount - hardwareCount > 0) {
                var color = isRed ? "#ff0014" : isOrange ? "#f93" : isYellow ? "#ffe900" : isBlue ? "#0858f5" : "green";
                $(".normal").css("background-color", color);
                $(".warningcount").css("color", "white");
                $(".normal .result").text("异常");
            } else {
                $(".normal .result").text("正常");
            }

            if (htmls != "") {
                if ($(".warningnotice div ul").html() == "") {
                    $(".warningnotice div ul").html(htmls);
                } else {
                    $(".warningnotice div ul li").before(htmls);
                }
            }

            setTimeout(function () {
                if ($("#ModelShowType").data("showedtype") == "three3d") {
                    if ($("#three3dcanvas_framework").find(".m-loading").length == 0) {
                        $.map3DMaker.showPointStatus();
                    } else {
                        three3dloadingstatutimer = setInterval(function () {
                            if ($("#three3dcanvas_framework").find(".m-loading").length == 0) {
                                $.map3DMaker.showPointStatus();
                                window.clearInterval(three3dloadingstatutimer);
                            }
                        }, 500);
                    }

                } else if ($("#ModelShowType").data("showedtype") == "mapmodel") {
                    if (maploadinged) {
                        ShowMapPointMarkerStatus();
                    } else {
                        maploadingstatutimer = setInterval(function () {
                            if (maploadinged) {
                                ShowMapPointMarkerStatus();
                                window.clearInterval(maploadingstatutimer);
                            }
                        }, 500);
                    }
                }
            }, 2000);
            newLoadingStatus = 1;
        } else {
            console.log("加载报警概况信息时出错：" + result.Message);
            $(".warningnotice .warningnum").text("NULL");
        }
    });
}

function ShowMapPointMarkerStatus() {
    var u = $("#monitorPoint .addpointtypepanel").find(".menu_sec_name");
    for (var i = 0; i < u.length; i++) {
        var typeid = $(u[i]).data("pointtypeid");
        var id = $(u[i]).data("pointid");
        var statu = $(".device_" + typeid + "_" + id + " .state").data("pointstatus");

        $("#mapmarker_" + id).removeClass("mappointstatus_0").removeClass("mappointstatus_1").removeClass("mappointstatus_2").removeClass("mappointstatus_3").addClass("mappointstatus_" + statu);
        $("#mapmarkercontent_" + id).removeClass("amapmarkercontentstatus_0").removeClass("amapmarkercontentstatus_1").removeClass("amapmarkercontentstatus_2").removeClass("amapmarkercontentstatus_3").addClass("amapmarkercontentstatus_" + statu);
        $("#mapmarker_" + id).parent().addClass("mappointstatus_" + statu);
    }
}

function removeWaringStatusClass(pointname) {
    var className = "warnging_" + pointname;
    $(".noticeMsg li").removeClass(className + "_0").removeClass(className + "_1").removeClass(className + "_2").removeClass(className + "_3");
}

function LoadRoleSettingMenus(rolesettingmenudata) {
    if (rolesettingmenudata.length == 0) {
        $("#settingmenus").empty();
        $("#settingmenus").hide();
        return;
    }

    $("#settingmenus").show();
    var rolesettingmenuhtmls = "";
    rolesettingmenuhtmls += '<ul class="clearfix">';
    for (var i = 0; i < rolesettingmenudata.length; i++) {
        rolesettingmenuhtmls += '<li onclick="ShowSystemSettingWindow(this)" data-functionid="' + rolesettingmenudata[i].I + '" data-functionname="' + rolesettingmenudata[i].N + '" data-href="' + rolesettingmenudata[i].A + '">' +
            '<i class="ico ico-' + rolesettingmenudata[i].I + '-setting"></i>' +
            '<span><a href="javascript:void(0)">' + rolesettingmenudata[i].N + '</a></span>' +
            '</li>';
    }
    rolesettingmenuhtmls += "</ul>";
    $("#settingmenus").html(rolesettingmenuhtmls);
}

function ShowSystemSettingWindow(obj) {
    var showid = $(obj).data("functionid");
    InstailSystemSettingContent(showid);
    showBigDialog(500, "Model_SystemSettingWindow");
}

function Logout() {
    //var allCookie = document.cookie.split(";");
    //for (var i = 0; i < allCookie.length; i++) {
    //    var cname = allCookie[i].split("=")[0].toString();
    //    $.cookie(cname, "", { expires: -1, path: '/' });
    //}
    //location.href = '/account/loginout';
    location.href = '/account/SignOut';
}

function LogoutSetting() {
    layer.confirm('您确定退出吗？直接退出将不保存本次更改！', {
        btn: ['直接退出', '取消退出']
    }, function () {
        DeleteBridgeAllCookie();
        location.href = "/Home/Index/" + $("#BridgeId").val();
    });
}

function SaveSetting() {
    layer.confirm('您确定发布吗？请检查设置项目是否正确！', {
        btn: ['已检查直接发布', '暂不发布']
    }, function () {
        loaddingshow();
        $.post("/Setting/SaveEdit_SaveSetting", { bridgeid: $("#BridgeId").val() }, function (result) {
            if (result === "") {
                loaddinghide();
                layer.confirm('已正确发布！您需要退出编辑吗？', {
                    btn: ['退出编辑', '继续编辑']
                }, function () {
                    ClearMonitorSettingData();
                    DeleteBridgeAllCookie();
                    location.href = "/home/index/" + $("#BridgeId").val() + "?isfromedit=true";
                }, function () {
                    loaddinghide();
                });
            } else {
                layer.alert("错误:" + result.Message, { title: "错误提示" });
                loaddinghide();
                layer.confirm('您需要退出编辑吗？', {
                    btn: ['退出编辑', '继续编辑']
                }, function () {
                    ClearMonitorSettingData();
                    DeleteBridgeAllCookie();
                    location.href = "/home/index/" + $("#BridgeId").val() + "?isfromedit=true";
                }, function () {
                    loaddinghide();
                });
            }

        });
    });
}

function GoBridge(id) {
    DeleteBridgeAllCookie();
    location.href = "/Home/Index/" + id;
}

function SetStartGoMonitorAllCookie() {
    var allCookie = document.cookie.split(";");
    for (var i = 0; i < allCookie.length; i++) {
        var cname = $.trim(allCookie[i].split("=")[0].toString());
        if (cname.indexOf("" + $("#BridgeId").val()) === -1) {
            if (cname.indexOf("slope_menusdata_") > -1 || cname.indexOf("slope_rolesettingmenusdata_") > -1 || cname.indexOf("slope_IsFirstLoad3dModelCount_") > -1) {
                $.cookie(cname, "", { expires: -1, path: '/' });
            }
        }
    }
}
function DeleteBridgeAllCookie() {
    var menudatacookie = 'slope_menusdata_' + $("#BridgeId").val() + "_" + $("#RoleId").val();
    $.cookie(menudatacookie, '', { expires: -1, path: '/' });//当前桥菜单信息
    var roledatacookie = 'slope_rolesettingmenusdata_' + $("#BridgeId").val() + "_" + $("#RoleId").val();
    $.cookie(roledatacookie, '', { expires: -1, path: '/' });//当前桥角色权限信息
    var firstmodelloadcookie = 'slope_IsFirstLoad3dModelCount_' + $("#BridgeId").val();
    $.cookie(firstmodelloadcookie, '', { expires: -1, path: '/' });
}

function showDialog(width, id, zindex) {
    $('#monitorModal .modal-dialog').attr("style", "min-width:" + width + "px;");
    $("#monitorModal .modal-content").hide();
    $("#" + id).show();
    $(".modal-backdrop").show();
    $('#monitorModal').modal('show');
    $('#monitorModal').addClass('in');
    $('#monitorModal').show();
    if (zindex != undefined) {
        $("#" + id).parents(".modal").attr("style", "z-index:" + zindex);
    }
    $("#" + id).parent().parent().show();
}
function showDragDialog(id) {
    $("#" + id).addClass("in").show();
    $(".modal-backdrop").remove();
}
function showBigDialog(width, id) {
    $('#monitorBigModal .modal-dialog').attr("style", "min-width:" + width + "px;");
    $("#monitorBigModal .modal-content").hide();
    $("#" + id).show();
    $(".modal-backdrop").show();
    $('#monitorBigModal').modal('show');
    $('#monitorBigModal').show();
}

function hideDialog() {
    $("#monitorModal").hide();
    $(".modal-backdrop").remove();
    $(".layui-layer-move").remove();
}
function hidBigeDialog() {
    $("#monitorModal").hide();
}
function hideDragDialog() {
    $(".dragdialogwindow").hide();
    $(".modal-backdrop").remove();
}

function SaveVideoOverviewOrderNum() {
    var menus = $("#overviewwindowli_7").find(".reveal_drag");
    for (var i = 0; i < menus.length; i++) {
        $(menus[i]).find(".video-js").data("order", i + 1);
    }
    var newResult = "";
    for (var k = 0; k < menus.length; k++) {
        if ($(menus[k]).css("display") != 'none') {
            var newid = $(menus[k]).find(".video-js").data("id");
            var neworder = $("#realvideo_" + newid).data("order");
            newResult += newid + "," + neworder + "|";
        }
    }
    $.post("/Setting/SaveEdit_SaveMonitorObjectVideoOverviewOrder", { monitorobjectid: $("#BridgeId").val(), orders: newResult }, function (data) {
        if (data)
            layer.msg("视频监控排序信息已保存");
        else
            layer.msg("视频监控排序信息保存失败");
    });
}
//保存 菜单功能 排序
function SaveFeaturesOrderNum() {
    var menus = $("#menuul").find(".menudrag");
    for (var i = 0; i < menus.length; i++) {
        $(menus[i]).data("order", i + 1);
    }
    var newResult = "";
    for (var k = 0; k < menus.length; k++) {
        var newid = $(menus[k]).data("id");
        var neworder = $("#menu_" + newid).data("order");
        newResult += newid + "," + neworder + "|";
    }
    $.post("/Setting/SaveEdit_SaveBridgeFeaturesOrder", { bridgeid: $("#BridgeId").val(), orders: newResult }, function () {
        layer.msg("功能菜单排序信息已保存");
    });
}

function SavePointTypeOverviewOrderNum() {
    var menus = $("#overviewwindowli_2").find(".reveal_drag");
    for (var i = 0; i < menus.length; i++) {
        $(menus[i]).data("order", i + 1);
    }
    var newResult = "";
    for (var k = 0; k < menus.length; k++) {
        if ($(menus[k]).css("display") != 'none') {
            var newid = $(menus[k]).data("id");
            var neworder = $("#realdatapointtype_" + newid).data("order");
            newResult += newid + "," + neworder + "|";
        }
    }
    $.post("/Setting/SaveEdit_SaveBridgePointTypeOverviewOrder", { bridgeid: $("#BridgeId").val(), orders: newResult }, function (data) {
        if (data)
            layer.msg("监测类型排序信息已保存");
        else
            layer.msg("监测类型排序信息保存失败");
    });
}

//保存右侧 概况下的三个子块 序号
function SaveRightWindowOverviewOrderNum() {
    var lis = $("#rightwindow_overview").find(".survey_drag");
    for (var i = 0; i < lis.length; i++) {
        $(lis[i]).data("order", i + 1);
    }
    var newLis = "";
    for (var k = 0; k < lis.length; k++) {
        var newid = $(lis[k]).data("key");
        var neworder = $("#overviewwindowli_" + newid).data("order");
        newLis += newid + "," + neworder + "|";
    }
    $.post("/Setting/SaveEdit_SaveRightWindowOverviewOrder", { bridgeid: $("#BridgeId").val(), orders: newLis }, function () {
        layer.msg("概况功能模块排序信息已保存");
    });
}

function DeleteMenu(obj) {
    //删除对应功能菜单
    var id = $(obj).parent().parent().parent().data("id");
    $.post("/Setting/SaveEdit_DeleteBridgeFeatures", { bridgeid: $("#BridgeId").val(), id: id });
    $("#menuul_add_" + id).show(500);
    $("#menu_" + id).remove();
    layer.msg("功能菜单删除成功");
}

function EditMenuText(a) {
    //编辑对应功能菜单
    $(a).parent().parent().parent().find("a span").hide();
    $(a).parent().parent().parent().find(".dropdown-toggle").hide();
    $(a).parent().parent().parent().find(".setnewmenutext").show();
}
function SaveEditMenuText(text) {
    //编辑对应功能菜单
    var v = $.trim($(text).val());
    if (v == "") {
        layer.msg("菜单名称不能为空");
        return;
    }
    $.post("/Setting/SaveEdit_BridgeFeatures", { bridgeid: $("#BridgeId").val(), featureid: $(text).parent().parent().parent().data("id"), featurevalue: v }, function (data) {
        $(text).parent().parent().find("span").text(v);
        $(text).parent().hide();

        $(text).parent().parent().find("span").show();
        $(text).parent().parent().parent().find(".dropdown-toggle").show();

        layer.msg("菜单名称已成功保存");
    });
}
function Edit_UpdateSystemLogo(e) {
    var oldurl = $(e).data("logo");
    $("#Model_System_UpdateLogo_Window .modal-body .conent img").attr("src", "/" + oldurl);
    showDialog(600, "Model_System_UpdateLogo_Window");
}
function SysLogoFileChanger(e) {
    var formData = new FormData();
    var files = $("#Model_System_UpdateLogo_Window #syslogoupload")[0].files[0];
    formData.append("file", files);
    formData.append("bridgeid", $("#BridgeId").val());
    $.ajax({
        url: '/FileUpload/Upload',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function (res) {
            oldurl = res.path;
            $("#Model_System_UpdateLogo_Window .modal-body .conent img").data("path", oldurl);
            $("#Model_System_UpdateLogo_Window .modal-body .conent img").attr("src", "/" + oldurl);
            $(".saveslogobtn").removeAttr("disabled");
            $(".saveslogobtn").removeClass("btnnotclick");
        }
        , error: function (res) {
            layer.alert("LOGO上传失败");
            $(".saveslogobtn").attr("disabled", "disabled");
            $(".saveslogobtn").addClass("btnnotclick");
        }
    });
}
function SaveSystemLogo_Window() {
    var path = $("#Model_System_UpdateLogo_Window .modal-body .conent img").data("path");
    $.post("/Setting/SaveEdit_UpdateDepartmentSystemLogo", { bridgeid: $("#BridgeId").val(), logopath: path }, function (res) {
        if (res.toString().toLowerCase() === "true") {
            layer.msg("保存成功");
            $(".navbar-header .navbar-brand img").attr("src", "/" + path);
            hideDialog("Model_System_UpdateLogo_Window");
        }
        else {
            layer.alert("保存失败");
        }
    });
}
function Edit_UpdateSystemName(i) {
    $(i).parent().find("span").hide();
    $(i).parent().find("i").hide();
    $(i).parent().find("input[type='text']").show().focus();
    enterEventInput = $(i).parent().find("input[type='text']");
}
function SaveEditSystemName(text) {
    var v = $.trim($(text).val());
    if (v == "") {
        layer.msg("系统名称不能为空");
        return;
    }
    $.post("/Setting/SaveEdit_UpdateDepartmentSystemName", { bridgeid: $("#BridgeId").val(), depid: $.trim($("#depid").val()), sysname: v }, function (data) {
        $(text).parent().find("span").text(v);
        $(text).parent().find("span").show();
        $(text).hide();
        $(text).parent().parent().find("i").show();
        layer.msg("系统名称已成功保存");
    });
}

function Edit_UpdateBridgeName(i) {
    $(i).parent().parent().find(".bridgeName").find("span").hide();
    $(i).parent().hide();
    $(i).parent().parent().find(".bridgeName").find(".bridgenametext").show().focus();
    enterEventInput = $(i).parent().parent().find(".bridgeName").find(".bridgenametext");
}
function SaveEditBridgeName(text) {
    var v = $.trim($(text).val());
    if (v == "") {
        layer.msg("桥梁名称不能为空");
        return;
    }
    $.post("/Setting/SaveEdit_BridgeName", { bridgeid: $("#BridgeId").val(), bridgename: v }, function (data) {
        $(text).parent().find("span").text(v);
        $(text).parent().find("span").show();
        $(text).hide();
        $(text).parent().parent().find(".editable").show();
        layer.msg("桥梁名称已成功保存");
    });
}

/**
 * 新增菜单
 * @param icon 菜单图标的className
 * @param name 菜单名称
 * @param settingUrl 设置的href地址（a标签）
 */
function Set_AddMenus(id, name) {
    var listr = '<li class="sideBar_drag dropdown menudrag" id="menu_' + id + '" style="visibility: visible;" data-order="' + id + '" data-id="' + id + '">' +
        '<a href="javascript:void(0)">' +
        '<i class="ico ico-sideBar-' + id + '"></i>' +
        '<span>' + name + '</span>' +
        '<p class="setnewmenutext">' +
        '<input type="text" value="' + name + '" onblur="SaveEditMenuText(this);" maxlength="20">' +
        '</p>' +
        '</a>' +
        '<i class="ico ico-sideBar-more editable dropdown-toggle" data-toggle="dropdown" style="display: inline;"></i>' +
        '<ul class="dropdown-menu scroll">' +
        '<li><a href="javascript:(0);" onclick="EditMenuText(this);">重命名</a></li>' +
        '<li><a href="javascript:(0);" onclick="DeleteMenu(this);">删除</a></li>' +
        '</ul>' +
        '<i class="ico ico-drag editable" style="display: inline;"></i>' +
        '</li>';
    $.post("/Setting/SaveEdit_AddBridgeFeatures", { bridgeid: $("#BridgeId").val(), featureid: id }, function (data) {
        $("#menuul").append(listr);
        $("#menuul_add_" + id).hide();
        $(".addModulePop").hide();
        $('.sideBar_drag_box .sideBar_drag').arrangeable({
            dragSelector: '.ico-drag', direction: 'y', myDragEnd: function (data) {
                SaveFeaturesOrderNum();
            }
        });
    });
}

function SaveModelUploadData() {
    loaddingshow();
    $.post("/Setting/SaveEdit_SaveModelUploadData", { bridgeid: $("#BridgeId").val(), bridgemodels: JSON.stringify(bridgemodeldatas), mapmodels: JSON.stringify(mapmodeldatas) }, function (result) {
        hideDialog();
        layer.msg('保存成功,正尝试加载模型,请稍后...');
        $("#ModelParameters").val("[]");
        setTimeout(function () { EditShow3DModel(); }, 1000);
    });
}

function Set_AddRightOverviewWindow(obj) {
    var overviewkey = $(obj).data("key");
    $.post("/Setting/SaveEdit_AddRightOverviewWindow", { bridgeid: $("#BridgeId").val(), overviewkey: overviewkey }, function (result) {
        $(obj).hide();
        if (overviewkey === 0) {//监测指标
            $("#ScoreIndicatorsIsShow").val("True");
            ShowWindowData_ScoreIndicators();
        }
        else if (overviewkey == 7) {//视频监控
            if ($("#overviewwindowli_7").length == 0) {
                $("#rightwindow_overview").append('<div id="overviewwindowli_7" class="survey_drag overviewwindowli7" style="display:block;" data-key="7" data-order="7">' +
                    '<span class="drag_btn editable"><i class="ico ico-drag"></i></span>' +
                    '<div id="videostasticscontent" class="clearfix">' +
                    '<ul class="video_drag_box clearfix videoList" id="videoList"></ul>' +
                    '<span class="monitorType editable">' +
                    '<span onclick="Edit_Overview_Video_Window();">' +
                    '<i class="ico ico-add-radius"></i>添加视频监控' +
                    '</span>' +
                    '<span class="dropup fr">' +
                    '<i class="ico ico-sideBar-more dropdown-toggle" data-toggle="dropdown"></i>' +
                    '<ul class="dropdown-menu scroll">' +
                    '<li><a href="javascript:void(0);" onclick="Set_RightVideoShowWindowType(1)">1分屏</a></li>' +
                    '<li><a href="javascript:void(0);" onclick="Set_RightVideoShowWindowType(2)">2分屏</a></li>' +
                    '<li><a href="javascript:void(0);" onclick="Set_DeleteRightOverviewWindow(7)">删除</a></li>' +
                    '</ul>' +
                    '</span>' +
                    '</span>' +
                    '</div>' +
                    '</div>');
            }
            ShowWindowData_VideoStastics();
        }
        $("#overviewwindowli_" + overviewkey).show(100);
    });
}


function ShowBridgeModel(type) {
    $(".modelmaptools item").removeClass("active");
    $(".modelmaptools ." + type + "showtype").addClass("active");
    if (type === "model3d") {
        $("#ModelShowType").data("showedtype", "three3d");
        if ($("#hidemodel3dbtn").val() === "false") {
            $("#mapmodel").css('zIndex', '0');
            $(".mapCenter").removeClass('active');
            if ($("#model3d").html() === "") {
                var isedit = "false";
                $.get("/Model/Index/" + $("#BridgeId").val(), {
                    isedit: isedit,
                    hide3dresetbtn: $("#hide3dresetbtn").val(),
                    hide3dgridbtn: $("#hide3dgridbtn").val()
                }, function (result) {
                    $("#model3d").html(result);
                    if (result != "") {
                        init3d();
                    }
                });
            }
            $("#model3d").css('zIndex', '1');
            $(".relitubtn").show();
            $(".modelbridge").show();
            $("#relitutable").hide();
            //隐藏温度热力图按钮
            if ($("#setpointtypepanel_2").length === 0) {
                $(".templateModelShowBtn").hide();
            }
        }
        $.map3DMaker.setIsResetPointSence();
    }
    else {
        $("#ModelShowType").data("showedtype", "mapmodel");
        $("#model3d").css('zIndex', '0');
        if ($("#mapmodel").html() === "") {
            $.get("/Model/ModelMap/" + $("#BridgeId").val(),
                {
                    isedit: "false",
                    hide3dresetbtn: $("#hide3dresetbtn").val(),
                    hide3dgridbtn: $("#hide3dgridbtn").val()
                },
                function (result) {
                    $("#mapmodel").html(result);
                    if (result !== "") {
                        init3dmodelmap();
                    }
                });
        }
        $("#mapmodel").css('zIndex', '1');
        $(".mapCenter").addClass('active');
        $(".relitubtn").hide();
        $(".modelbridge").hide();
        $("#relitutable").hide();
    }
    setTimeout(function () { LoadLayoutWarningInfo(); }, 1000);
}

function Set_DeleteRightOverviewWindow(id) {
    $.post("/Setting/SaveEdit_DeleteRightOverviewWindow", { bridgeid: $("#BridgeId").val(), overviewkey: id }, function (result) {
        $("#overviewwindowli_" + id).hide(100);
        $("#addrightoverviewmenus_" + id).show(100);
    });
}

function LoadData_Overview_Score_Window() {
    var indicatorhtmls = "";
    var oldsectionids = $("#allScoreIndicatorsSectionIds").val().split(',');
    $("#ScoreIndicators_NewWindowRefreshSecond").val($("#ScoreIndicatorsRefreshSecond").val());
    $.post("/Setting/GetAllSections", { bridgeid: $("#BridgeId").val() }, function (result) {
        var data = $.parseJSON(result);
        for (var j = 0; j < data.length; j++) {
            var checked = oldsectionids.contains(data[j].Id) ? "checked" : "";
            indicatorhtmls += '<li><label class="checkbox"><input name="indicators_sections" type="checkbox" id="indicators_sections_' + data[j].Id + '" data-sectionid="' + data[j].Id + '" ' + checked + '><span> ' + data[j].Name + '</span></label></li>';
        }
        if (indicatorhtmls == "") {
            $(".scoreindicators").html("<span>当前没有添加任何子结构信息</span>");
        } else {
            var allbridgechecked = oldsectionids.contains(0) ? "checked" : "";
            indicatorhtmls += '<li><label class="checkbox"><input name="indicators_sections" type="checkbox" id="indicators_sections_0" data-sectionid="0" ' + allbridgechecked + '><span>整桥</span></label></li>';
            $("#Model_Overview_Score_Window .modal-body ul li div ul").html(indicatorhtmls);
        }
    });
}

function LoadData_Overview_PointData_Window() {
    $.post("/Setting/GetWindowPointDataStasticsData", { bridgeid: $("#BridgeId").val() }, function (result) {
        var datas = $.parseJSON(result);
        console.log(datas);
        var htmls = '';
        for (var i = 0; i < datas.length; i++) {
            if (datas[i].PointTypeName !== "视频") {
                htmls += '<li class="pointdatastastics_li">' +
                    '<input type="checkbox" id="pointdatastastics_' + datas[i].PointTypeId + '" data-pointtypeid="' + datas[i].PointTypeId + '" ' + (datas[i].IsShow ? 'checked' : '') + '/>' +
                    '<label for="pointdatastastics_' + datas[i].PointTypeId + '">' + datas[i].PointTypeName + '</label>' +
                    '<div>' +
                    '<ul class="clearfix">' +
                    '<li>数据范围:<input type="text" value="' + datas[i].DataAreaValue + '" class="DataAreaValue"/>天</li>' +
                    '<li>刷新频率:<input type="text" value="' + datas[i].RefreshValue + '" class="RefreshValue"/>秒</li>' +
                    '</ul>' +
                    '</div>' +
                    '</li>';
            }
        }
        $("#Model_Overview_PointData_Window .modal-body ul").html(htmls);
    });
}

function LoadData_Overview_PointType_Window() {
    var pointtypehtmls = "";
    $.post("/Setting/GetAllNotShowPointTypesOverviews", { bridgeid: $("#BridgeId").val() }, function (result) {
        var data = $.parseJSON(result);
        for (var j = 0; j < data.length; j++) {
            pointtypehtmls += '<li><label class="checkbox"><input name="pointtypeoverview_pointtypes" type="checkbox" id="pointtypeoverview_pointype_' + data[j].Id + '" data-id="' + data[j].Id + '"><span> ' + data[j].Name + '</span></label></li>';
        }
        $("#Model_Overview_PointTypeOverview_Window .modal-body ul li div ul").html(pointtypehtmls);
    });
}

function LoadData_Overview_PointOverview_Window() {
    var refreshValue = $.trim($("#PointOverviewRefreshSecond").val());
    $("#PointOverview_NewWindowRefreshSecond").val(refreshValue);
}

function SaveWindowSettingPointOverviewWindow() {
    var refreshValue = $.trim($("#PointOverview_NewWindowRefreshSecond").val());

    if (refreshValue == "0" || refreshValue == "" || !ValidateNum(refreshValue)) {
        layer.alert("刷新频率输入错误", { title: "错误提示" });
        return;
    }
    loaddingshow();
    $.post("/Setting/SaveWindowSettingPointOverviewWindow", { BridgeId: $("#BridgeId").val(), refreshValue: refreshValue }, function (result) {
        if (result) {
            layer.msg("保存成功！");
            hideDialog();
            $("#PointOverviewRefreshSecond").val(refreshValue);
            ShowWindowData_PointOverview_Setting();
        } else {
            layer.msg("保存失败！");
        }
        loaddinghide();
    });
}

function SaveWindowSettingScoreIndicatorWindow() {
    var refreshValue = $.trim($("#ScoreIndicators_NewWindowRefreshSecond").val());
    var scoreindicatorsections = "";
    $('input[name="indicators_sections"]:checked').each(function () {
        scoreindicatorsections += $(this).data("sectionid") + ",";
    });
    if (refreshValue == "0" || refreshValue == "" || !ValidateNum(refreshValue)) {
        layer.alert("刷新频率输入错误", { title: "错误提示" });
        return;
    }
    scoreindicatorsections = scoreindicatorsections.substring(0, scoreindicatorsections.length - 1);
    if (scoreindicatorsections != "," && scoreindicatorsections != "" && refreshValue != "") {
        loaddingshow();
        $.post("/Setting/SaveWindowSettingScoreIndicatorWindow", { BridgeId: $("#BridgeId").val(), refreshValue: refreshValue, scoreIndicatorSectionIdStr: scoreindicatorsections }, function (result) {
            if (result) {
                layer.msg("保存成功！");
                hideDialog();
                $("#allScoreIndicatorsSectionIds").val(scoreindicatorsections);
                $("#ScoreIndicatorsRefreshSecond").val(refreshValue);
                ShowWindowData_ScoreIndicators();
            } else {
                layer.msg("保存失败！");
            }
            loaddinghide();
        });
    } else {
        layer.msg("监测指标不能为空！");
    }
}

function SaveWindowSettingPointTypeOverviewWindow() {
    var pointtypeoverviewtypeids = "";
    $('input[name="pointtypeoverview_pointtypes"]:checked').each(function () {
        pointtypeoverviewtypeids += $(this).data("id") + ",";
    });
    if (pointtypeoverviewtypeids == "" || pointtypeoverviewtypeids == ",") {
        layer.msg("未选择任何监测类型，无法保存");
        return;
    }
    pointtypeoverviewtypeids = pointtypeoverviewtypeids.substring(0, pointtypeoverviewtypeids.length - 1);
    loaddingshow();
    debugger
    $.post("/Setting/SaveWindowSettingPointTypeOverviewWindow", { monitorobjectId: $("#BridgeId").val(), showpointtypeidstr: pointtypeoverviewtypeids }, function (result) {
        if (result) {
            layer.msg("保存成功！");
            hideDialog();
            var newshowpointtypeoverviewtypes = pointtypeoverviewtypeids.split(',');
            for (var i = 0; i < newshowpointtypeoverviewtypes.length; i++) {
                $("#realdatapointtype_" + newshowpointtypeoverviewtypes[i]).show(100);
                LoadPointTypeOverviewDetailRealData(newshowpointtypeoverviewtypes[i]);
            }
        } else {
            layer.msg("保存失败！");
        }
        loaddinghide();
    });
}

function SaveWindowSettingPointDataStasticsWindow() {
    var alls = $("#Model_Overview_PointData_Window .modal-body ul").find(".pointdatastastics_li");
    var data = new Array();
    for (var i = 0; i < alls.length; i++) {
        var nData = new Object();
        nData.IsShow = $(alls[i]).find("input[type='checkbox']").prop("checked");
        nData.PointTypeId = $(alls[i]).find("input[type='checkbox']").data("pointtypeid");
        nData.RefreshValue = $(alls[i]).find(".RefreshValue").val();
        nData.DataAreaValue = $(alls[i]).find(".DataAreaValue").val();
        data.push(nData);
    }
    $.post("/Setting/SaveWindowSettingPointDataStasticsWindow", { BridgeId: $("#BridgeId").val(), datajsonstr: JSON.stringify(data) }, function (result) {
        if (result != "") {
            layer.msg("保存成功！");
            hideDialog();
            $("#PointDataStasticsDatas").val(result);
            ShowWindowData_PointDataOverview();
        } else {
            layer.msg("保存失败！");
        }
        loaddinghide();
    });
}

function GetNewTablePageContent(allcount, allpage, nowpage, time, onclickfun) {
    var pageType = "";
    if (time == "" || time == undefined) {
        pageType = onclickfun + "('#GoPage#')";
    } else {
        pageType = onclickfun + "('" + time + "','#GoPage#')";
    }
    var code = "<span>共<b>" + allcount + "</b>条 合计<b id='" + onclickfun + "_AllPage'>" + allpage + "</b>页</span>";
    if (nowpage > 1) {
        code += '<a class="countpage" href="javascript:void(0);" onclick="' + pageType.replace("#GoPage#", "1") + '">首页</a> ';
        code += '<a class="countpage" href="javascript:void(0);" onclick="' + pageType.replace("#GoPage#", (nowpage - 1)) + '">上一页</a> ';
    }
    else {
        code += '<a class="none" href="javascript:void(0);" onclick="">首页</a> ';
        code += '<a class="none" href="javascript:void(0);" onclick="">上一页</a> ';
    }
    if (nowpage > 2) {
        for (var j = 4; j > 0; j--) {
            if (nowpage - j >= 1) {
                code += '<a class="countpage" href="javascript:void(0);" onclick="' + pageType.replace("#GoPage#", nowpage - j) + '">' + (nowpage - j) + '</a> ';
            }
        }
    } else if (nowpage == 2) {
        code += '<a class="countpage" href="javascript:void(0);" onclick="' + pageType.replace("#GoPage#", "1") + '">1</a> ';
    }
    code += '<a class="countpage active" href="javascript:void(0);" onclick="">' + nowpage + '</a> ';
    for (var i = nowpage + 1; i < nowpage + 5; i++) {
        if (i < allpage + 1)
            code += '<a class="countpage" href="javascript:void(0);" onclick="' + pageType.replace("#GoPage#", i) + '">' + i + '</a> ';
    }
    if ((nowpage + 5) < allpage)
        code += '<a class="countpage" href="javascript:void(0);" onclick="' + pageType.replace("#GoPage#", nowpage + 1) + '">...</a> ';
    if (nowpage < allpage)
        code += '<a class="countpage" href="javascript:void(0);" onclick="' + pageType.replace("#GoPage#", nowpage + 1) + '">下一页</a>';
    if (nowpage == allpage) {
        code += '<a class="none" href="javascript:void(0);" onclick="">下一页</a>';
        code += '<a class="none" href="javascript:void(0);" onclick="">尾页</a>';
    }
    else {
        code += '<a class="countpage" href="javascript:void(0);" onclick="' + pageType.replace("#GoPage#", allpage) + '">尾页</a>';
    }
    code += '<span style="margin-right: -8px;margin-left: 5px;">跳转：</span><input type ="text" id="' + onclickfun + '_GoPage" data-func="' + onclickfun + '" data-time="' + time + '" class="countpage" href="javascript:void(0);" /><a href="javascript:void(0);" class="countpage" onclick="NewWindowPageGoPage(\'' + onclickfun + '\')">跳转</a>';
    return code;
}

function isInteger(x) {
    return x % 1 === 0;
}
function NewWindowPageGoPage(func) {
    var value = $.trim($("#" + func + "_GoPage").val());
    if (value != "" && isInteger(value)) {
        if (value < 1 || value > (($("#" + func + "_AllPage").text()) * 1)) {
            layer.msg("请输入合适的页数!");
            $("#" + func + "_GoPage").focus();
            $("#" + func + "_GoPage").css("border", "1px solid red");
            return;
        }
        $("#" + func + "_GoPage").css("border", "1px solid #E8E8E8");
        eval(func + "('" + $("#" + func + "_GoPage").data("time") + "','" + value + "')");
    } else {
        layer.msg("请输入正确页数!");
        $("#" + func + "_GoPage").focus();
        $("#" + func + "_GoPage").css("border", "1px solid red");
    }
};
/**
 * *获取主页高程位移，水平位移，土压力数据并设置echart
 */
function setIndexChart() {

}
function ShowWindowData_ScoreIndicators() {
    var showSectionids = $("#allScoreIndicatorsSectionIds").val().split(',');
    var sectionids = "";
    for (var i = 0; i < showSectionids.length; i++) {
        sectionids += showSectionids[i] + ",";
    }
    $("#scoreoverviewchart").html("<span>加载中...</span>");
    $.get($("#DataApiAddress").val() + "api/data/windowdata/getscoreindicatorsdatas/" + $("#BridgeId").val() + "/" + sectionids, {}, function (result) {
        if (result.Code == 200) {
            $("#scoreoverviewchart").removeAttr("_echarts_instance_");
            var data = $.parseJSON(result.Result);
            var listdata = data.ScoreDatas;
            var seriesdata = [], indicatordata = [], overallScore = 0;
            for (var j = 0; j < listdata.length; j++) {
                if (listdata[j].layer == 1) {
                    overallScore = listdata[j].value;
                    continue;
                }
                seriesdata.push(listdata[j].value);
                indicatordata.push({ name: listdata[j].name, max: 100 });
            }
            var overdateChart = echarts.init(document.getElementById("scoreoverviewchart"));
            var option = {
                legend: {
                    bottom: 5,
                    itemGap: 20,
                    textStyle: {
                        color: '#fff',
                        fontSize: 14
                    },
                    selectedMode: 'single'
                },
                radar: {
                    indicator: indicatordata,
                    shape: 'circle',
                    splitNumber: 5,
                    name: {
                        textStyle: {
                            color: '#ffffff'
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            color: ["#44515d"],
                            type: 'dashed'
                        }
                    },
                    splitArea: {
                        show: false
                    },
                    axisLine: {
                        lineStyle: {
                            color: '#44515d'
                        }
                    }
                },
                series: [
                    {
                        name: '饼形图',
                        type: 'radar',
                        lineStyle: {
                            normal: {
                                width: 1,
                                opacity: 0.5
                            }
                        },
                        data: [seriesdata],
                        symbol: 'none',
                        itemStyle: {
                            normal: {
                                color: '#0076ff  '
                            }
                        },
                        areaStyle: {
                            normal: {
                                opacity: 0.6
                            }
                        }
                    },
                ]
            };
            if (option && typeof option === "object") {
                overdateChart.setOption(option, true);
            }

            //echarts.init(document.getElementById('scoreoverviewchart')).setOption({
            //    title: {
            //        text: ''
            //    },
            //    tooltip: {},
            //    legend: {
            //        data: ['']
            //    },
            //    radar: {
            //        name: {
            //            textStyle: {
            //                color: '#fff',
            //                backgroundColor: '#999',
            //                borderRadius: 3,
            //                padding: [5, 5, 7, 5]
            //            }
            //        },
            //        indicator: indicatordata
            //    },
            //    series: [{
            //        name: '监测指标分析',
            //        type: 'radar',
            //        data: [
            //            {
            //                value: seriesdata,
            //                name: '监测指标'
            //            }
            //        ]
            //    }]
            //});
            $("#overviewwindowli_0").find(".num").html(overallScore);
        } else {
            $("#scoreoverviewchart").html("<span>加载失败</span>");
            console.log("加载 概况 监测指标时发生错误：" + result.Message);
        }
    });
}

function GetPointStatus() {
    DevicePointStatus = [];
    $.get($("#HardwareAeroiotAppAddress").val() + "api/union/project/rate?project=" + $("#BridgeId").val(), {}, function (result) {
        console.log(result);
        DevicePointStatus = $.parseJSON(result);
    });
    return DevicePointStatus;
}
function ShowPointDeviceStasticsOverview() {
    $.get($("#DataApiAddress").val() + "api/points/getpointdevicestatus/" + $("#BridgeId").val(), {}, function (result) {
        if (result.Code == 200) {
            //恢复初始0数据
            var olds = $("#monitorPoint").find(".addpointtypepanel");
            for (var j = 0; j < olds.length; j++) {
                $(olds[j]).find("div a .num").text("0/" + $(olds[j]).find("div a .num").text().split('/')[1]);
            }
            for (var i = 0; i < result.Result.length; i++) {
                var n = result.Result[i];
                if (n.Status === 1) {
                    for (var tn = 0; tn < n.Types.length; tn++) {
                        $(".device_" + n.Types[tn] + "_" + n.Id).removeClass("badpoint").addClass("goodpoint");
                        var pointtypemenu = $(".device_" + n.Types[tn] + "_" + n.Id).parent().parent().parent().attr("id");
                        var counttext = $("#" + pointtypemenu + " div a .num").text().split('/');
                        var oldgoodcount = (counttext[0]) * 1 + 1;
                        $("#" + pointtypemenu + " div a .num").text(oldgoodcount + "/" + counttext[1]);
                    }
                } else {
                    $(".device_" + n.Types[tn] + "_" + n.Id).removeClass("goodpoint").addClass("badpoint");
                }
                for (var tn = 0; tn < n.Types.length; tn++) {
                    var oldstatus = $(".device_" + n.Types[tn] + "_" + n.Id + " .state").data("pointstatus");
                    if (n.Status === 1) {
                        //硬件正常
                        if (oldstatus !== PointStatus.Red && oldstatus !== PointStatus.Yellow && oldstatus !== PointStatus.Orange) {
                            $(".device_" + n.Types[tn] + "_" + n.Id + " .state").addClass("pointstatus_0");
                            $(".device_" + n.Types[tn] + "_" + n.Id + " .state").data("pointstatus", PointStatus.Green);
                        }
                    } else {
                        //硬件离线
                        if (oldstatus === PointStatus.Green || oldstatus === "") {
                            $(".device_" + n.Types[tn] + "_" + n.Id + " .state").addClass("pointstatus_3");
                            $(".device_" + n.Types[tn] + "_" + n.Id + " .state").data("pointstatus", PointStatus.Hardware);
                        }
                    }
                }
            }

            setTimeout(function () {
                LoadLayoutWarningInfo();//绑定完成后 触发一次 预警信息绑定
            }, 1000);
        } else {
            $("#pointoverviewleft").html("<span style='padding-top:30px;'>--</span>");
            $("#pointoverviewright").html("<span style='padding-top:30px;'>--</span>");
            console.log("加载 概况 传感器概况时发生错误：" + result.Message);
        }
    });
}
function ShowWindowData_PointOverview_Setting() {
    $("#pointoverviewleft").html("<span>加载中...</span>");
    $("#pointoverviewright").html("<span>加载中...</span>");

    $.get($("#DataApiAddress").val() + "api/points/getpointdevicestatus/" + $("#BridgeId").val(), {}, function (result) {
        if (result.Code == 200) {
            //恢复初始0数据
            var olds = $("#monitorPoint").find(".addpointtypepanel");
            for (var j = 0; j < olds.length; j++) {
                $(olds[j]).find("div a .num").text("0/" + $(olds[j]).find("div a .num").text().split('/')[1]);
            }
            var goodcount = 0;
            var badcount = 0;
            var allrate = 0;
            var badpointshtml = "<ul>";
            for (var i = 0; i < result.Result.length; i++) {
                var n = result.Result[i];
                if (n.Status === 1) {
                    goodcount++;
                    for (var tn = 0; tn < n.Types.length; tn++) {
                        $(".device_" + n.Types[tn] + "_" + n.Id).removeClass("badpoint").addClass("goodpoint");
                        var pointtypemenu = $(".device_" + n.Types[tn] + "_" + n.Id).parent().parent().parent().attr("id");
                        var counttext = $("#" + pointtypemenu + " div a .num").text().split('/');
                        var oldgoodcount = (counttext[0]) * 1 + 1;
                        $("#" + pointtypemenu + " div a .num").text(oldgoodcount + "/" + counttext[1]);
                    }
                } else {
                    badcount++;
                    badpointshtml += "<li>" + result.Result[i].Name + " 设备离线</li>";
                    $(".device_" + n.Types[tn] + "_" + n.Id).removeClass("goodpoint").addClass("badpoint");
                }
                for (var tn = 0; tn < n.Types.length; tn++) {
                    var oldstatus = $(".device_" + n.Types[tn] + "_" + n.Id + " .state").data("pointstatus");
                    if (n.Status === 1) {
                        //硬件正常
                        if (oldstatus !== PointStatus.Red && oldstatus !== PointStatus.Yellow && oldstatus !== PointStatus.Grap) {
                            $(".device_" + n.Types[tn] + "_" + n.Id + " .state").addClass("pointstatus_0");
                            $(".device_" + n.Types[tn] + "_" + n.Id + " .state").data("pointstatus", PointStatus.Green);
                        }
                    } else {
                        //硬件离线
                        if (oldstatus === PointStatus.Green || oldstatus === "") {
                            $(".device_" + n.Types[tn] + "_" + n.Id + " .state").addClass("pointstatus_3");
                            $(".device_" + n.Types[tn] + "_" + n.Id + " .state").data("pointstatus", PointStatus.Gray);
                        }
                    }
                }
                allrate += n.Rate;
            }
            var rates = (allrate / result.Result.length);
            rates = (rates + '' == "NaN") ? 0.0 : rates;
            rates = rates > 100 ? 100 : rates.toFixed(2);
            badpointshtml += "</ul>";

            //绑定左侧数据
            $("#pointoverviewleft").html('<span class="num">' + goodcount + '/' + result.Result.length + '</span><span>异常传感器&nbsp;&nbsp;&nbsp;<span class="org errorpointorg">' + badcount + '<div class="errorpointtips dropdown-menu scroll">' + badpointshtml + '</div></span></span>');
            //绑定右侧数据
            var badpercentage = ((badcount / result.Result.length) * 100).toFixed(2);
            var goodpercentage = ((goodcount / result.Result.length) * 100).toFixed(2);
            $("#pointoverviewright").removeAttr("_echarts_instance_");
            echarts.init(document.getElementById('pointoverviewright')).setOption({
                color: ['#00A0E9', '#387693'],
                legend: { orient: 'vertical', x: 'left', data: ['采集成功', '采集失败'] },
                series: [
                    {
                        name: '传感器采集成功率',
                        type: 'pie',
                        radius: ['50%', '70%'],
                        avoidLabelOverlap: false,
                        label: { normal: { show: false, position: 'center' }, emphasis: { show: true, textStyle: { fontSize: '13', fontWeight: 'bold' } } },
                        labelLine: { normal: { show: false } },
                        data: [{ value: rates }, { value: (100 - rates) }]
                    }
                ]
            });
            $("#pointoverviewright div").append("<p style='margin-top: 42%;'>" + rates * 1 + "%</p>");
            setTimeout(function () {
                LoadLayoutWarningInfo();//绑定完成后 触发一次 预警信息绑定
            }, 1000);
        } else {
            $("#pointoverviewleft").html("<span style='padding-top:30px;'>--</span>");
            $("#pointoverviewright").html("<span style='padding-top:30px;'>--</span>");
            console.log("加载 概况 传感器概况时发生错误：" + result.Message);
        }
    });
}
function EditPointTypeOverviewDetail(id, name) {
    $("#Model_Overview_PointTypeDetailOverview_Window").find(".modal-title").html(name + "概况信息编辑");
    $.post("/Setting/SaveEdit_GetAllShowPointDetail", { BridgeId: $("#BridgeId").val(), pointtypeid: id }, function (result) {
        $("#NowUpdateOverviewdPointTypeId").val(id);
        $("#NowUpdateOverviewdPointTypeCn").val(name);
        var pointdetails = $.parseJSON(result);
        if (name == "车流量") {
            $("#pointtypeoverview_cheliuliang").show();
            $("#pointtypeoverview_other").hide();
            $("#pointtypeoverview_cheliuliang").hide();
        }
        else if (name == "荷载") {
            $("#pointtypeoverview_hezai").show();
            $("#pointtypeoverview_hezai").hide();
            $("#pointtypeoverview_other").hide();

        } else {
            $("#pointtypeoverview_other").show();
            $("#pointtypeoverview_hezai").hide();
            $("#pointtypeoverview_cheliuliang").hide();

            var htmls = "";
            for (var i = 0; i < pointdetails.length; i++) {
                htmls += '<li><label class="checkbox"><input type="checkbox" id="pointtypeoverview_point_' + pointdetails[i].PointType + '_' + pointdetails[i].PointId + '" data-id="' + pointdetails[i].PointId + '"><span> ' + pointdetails[i].Name + '</span></label></li>';
            }
            $("#pointtypeoverview_other div ul").html(htmls);
        }

        //加载原数据
        $.post("/Setting/Get_EditPointTypeDataOverscoreData", { BridgeId: $("#BridgeId").val(), pointtypeid: id }, function (olddatastr) {
            var olddata = $.parseJSON(olddatastr);
            if (olddata.OverviewRealData != null) {
                if (olddata.OverviewRealData.PointIds != "" && olddata.OverviewRealData.PointIds != undefined) {
                    for (var j = 0; j < olddata.OverviewRealData.PointIds.length; j++) {
                        $("#pointtypeoverview_point_" + olddata.OverviewRealData.PointTypeId + "_" + olddata.OverviewRealData.PointIds[j]).attr("checked", 'true');
                    }
                }

                $("#pointtypeoverview_statisticstype_" + olddata.OverviewRealData.StatisticsType).attr("checked", 'checked');
                $("#pointtypeoverview_statisticsarea_" + olddata.OverviewRealData.StatisticsArea).attr("checked", 'checked');
                $("#pointtypeoverview_statistics_refresh_second").val(olddata.OverviewRealData.RefreshSecond);

            } else {
                $('input:radio[name="datastatisticstype"]').eq(0).attr("checked", 'checked');
                $('input:radio[name="datastatisticsarea"]').eq(0).attr("checked", 'checked');
            }
            showDialog(650, "Model_Overview_PointTypeDetailOverview_Window");
        });

    });
}
function DeletePointTypeOverviewDetail(id) {
    $.post("/Setting/SaveEdit_DeletePointTypeDetailOverviewWindow", { BridgeId: $("#BridgeId").val(), id: id }, function (result) {
        if (result) {
            layer.msg("删除成功");
            $("#realdatapointtype_" + id).hide();
            $("#pointtypeoverview_pointype_" + id).show();
        } else {
            layer.msg("保存失败！");
        }
    });
}
function DeleteBridgePoint(typeid, id) {
    layer.confirm('确认删除该测点？', function () {
        $.post("/Setting/SaveEdit_DeleteBridgePoint", { bridgeid: $("#BridgeId").val(), pointid: id }, function (reuslt) {
            if (reuslt) {
                layer.msg('删除成功');
                var npointshowcount = $("#monitorPoint").find(".set_pointli_" + id);
                for (var i = 0; i < npointshowcount.length; i++) {
                    var num = $(npointshowcount[i]).parent().parent().parent().find(".heading a .num").text().split('/')[1] * 1 - 1;
                    $(npointshowcount[i]).parent().parent().parent().find(".heading a .num").text("0/" + num);
                }
                $(".set_pointli_" + id).remove();
                if ($("#ModelShowType").data("showedtype") == "three3d") {
                    $.map3DMaker.deletPointByPointId(id);
                } else {
                    DeleteMapPointMarker([id]);
                }
                return;
            }
            layer.msg('删除失败');
        });
    });
}

function Save_EditPointTypeDataOverscoreData() {
    var pointtypeid = $("#NowUpdateOverviewdPointTypeId").val();
    var pointtypename = $("#NowUpdateOverviewdPointTypeCn").val();
    var pointdetailids = "";
    var fatherid = "";
    var datastatisticstype = $('input[name="datastatisticstype"]:checked').val();
    var datastatisticsarea = $('input[name="datastatisticsarea"]:checked').val();
    var refreshSecond = $("#pointtypeoverview_statistics_refresh_second").val();
    if (pointtypename == "车流量") {
        fatherid = "pointtypeoverview_cheliuliang";
    }
    else if (pointtypename == "荷载") {
        fatherid = "pointtypeoverview_hezai";

    } else {
        fatherid = "pointtypeoverview_other";
    }
    var points = $("#" + fatherid + " div ul").find("li");
    for (var i = 0; i < points.length; i++) {
        var check = $(points[i]).find("input[type='checkbox']");
        if (check.prop("checked")) {
            pointdetailids += $(check).data("id") + ',';
        }
    }
    if (pointdetailids == "" || pointdetailids == ",") {
        layer.msg("数据统计传感器未选择");
        return;
    }
    if (refreshSecond == "" || refreshSecond == 0) {
        layer.msg("数据刷新频率输入错误");
        return;
    }
    $.post("/Setting/Save_EditPointTypeDataOverscoreData", { BridgeId: $("#BridgeId").val(), pointtypeid: pointtypeid, pointids: pointdetailids, statisticsareaid: datastatisticsarea, statisticstypeid: datastatisticstype, refreshSecond: refreshSecond }, function (result) {
        if (result) {
            if (result != "false") {
                layer.msg("保存成功");
                hideDialog();
                $("#realdatapointtype_" + pointtypeid).data("realinfo", $.parseJSON(result));
                LoadPointTypeOverviewDetailRealData(pointtypeid);
            }
            else {
                layer.msg("保存失败");
            }
            loaddinghide();
        } else {
            layer.msg("保存失败！");
        }
    });
}

function LoadAddPointType() {
    var oldpointypes = $(".addpointtypepanel");
    for (var o = 0; o < oldpointypes.length; o++) {
        var id = $(oldpointypes[o]).data("id");
        $("#addpointtype_" + id).hide();
    }
    showDialog(500, "Model_Point_AddPointType_Window");
}

function Save_AddPointType() {
    var pointtypetypeids = "";
    $('input[name="addpointtype"]:checked').each(function () {
        if ($(this).parent().parent().css("display") != "none") {
            pointtypetypeids += $(this).data("id") + ",";
        }
    });
    if (pointtypetypeids == "" || pointtypetypeids == ",") {
        layer.msg("未选择任何传感器监测类型，无法保存");
        return;
    }
    $.post("/Setting/SaveEdit_AddBridgePointType", { BridgeId: $("#BridgeId").val(), typeidstr: pointtypetypeids }, function (result) {
        var datas = $.parseJSON(result);
        var htmlStr = "";
        for (var i = 0; i < datas.length; i++) {
            var pointshtmls = "";
            if (datas[i].Points !== null && datas[i].Points !== undefined) {
                for (var j = 0; j < datas[i].Points.length; j++) {
                    pointshtmls += '<li>' +
                        '<span class="state"></span>' +
                        '<span>' + datas[i].Points[j].Name + '</span>' +
                        '</li>';
                }
            }
            htmlStr += '<div class="panel addpointtypepanel" id="setpointtypepanel_' + datas[i].Id + '" data-id="' + datas[i].Id + '" data-name="' + datas[i].Name + '" onclick="SelectedPoints_PointType(' + datas[i].Id + ');">' +
                '<div class="heading">' +
                '<a class="collapsed" data-toggle="collapse" data-parent="#monitorPoint" href="#panel' + datas[i].Id + '" aria-expanded="false">' +
                '<i class="ico ico-data-' + datas[i].Id + ' mini"></i>' +
                '<span>' + datas[i].Name + '</span>' +
                '<span class="num">0/0</span>' +
                '<i class="ico ico-arrow-up fr"></i>' +
                '</a>' +
                '<span class="dropdown fr">' +
                '<i class="ico ico-sideBar-more dropdown-toggle" data-toggle="dropdown" aria-expanded="false"></i>' +
                '<ul class="dropdown-menu scroll">' +
                '<li><a href="javascript:void(0);" onclick="Save_AddPointFromPointType(' + datas[i].Id + ');">添点</a></li>' +
                '<li><a href="javascript:void(0);" onclick="Save_PointTypeStasticsShowTimes(' + datas[i].Id + ',\'' + datas[i].Name + '\');" style="' + (datas[i].Id == 33 ? "display:none" : "") + '">统计时间间隔</a></li>' +
                '<li><a href="javascript:void(0);" onclick="Save_DeletePointType(' + datas[i].Id + ');">删除</a></li>' +
                '</ul>' +
                '</span>' +
                '</div>' +
                '<div id="panel' + datas[i].Id + '" class="collapse" aria-expanded="false" style="height: 0px;">' +
                '<ul class="bodying">' +
                pointshtmls +
                '</ul>' +
                '</div>' +
                '</div>';
            $("#addpointtype_" + datas[i].Id).hide();
        }
        $('input[name="addpointtypefrom"]:checked').each(function () {
            $(this).removeAttr("checked");
        });
        hideDialog();
        loaddinghide();
        $("#monitorPoint").append(htmlStr);
        $("#addpointtypehtmlli").before(htmlStr);
    });
}

function Save_AddPointFromPointType(typeid) {
    var haveedTypes = $("#monitorPoint").find(".addpointtypepanel");
    var htmls = "";
    for (var i = 0; i < haveedTypes.length; i++) {
        var tid = $(haveedTypes[i]).data("id");
        var tname = $(haveedTypes[i]).data("name");
        htmls += '<label data-id="' + tid + '"><input name="addpoint_selecttype" type="checkbox" value="' + tid + '" ' + (typeid == tid ? "checked" : "") + '>' + tname + '</label>';
    }
    $("#addpointid").val("");
    $("#addpointname").removeAttr("disabled");
    $("#addpointname").val("");
    $("#addpointgroup").val("");
    $("#addpointinstalremark").val("");
    $("#pointtype_addpoint_pointtype").html(htmls);
    $("#pointtype_addpoint_pointtype").show();
    showDialog(250, "Model_AddPoint_Window", 1041);
}

function Edit_AddPointFromPointType(pointid) {
    $("#pointtype_addpoint_pointtype").html("");
    $("#pointtype_addpoint_pointtype").parent().hide();
    $.post("/Setting/GetPoint", { bridgeid: $("#BridgeId").val(), pointid: pointid }, function (pointstr) {
        var point = $.parseJSON(pointstr);
        $("#addpointid").val(pointid);
        $("#addpointname").attr("disabled", "disabled");
        $("#addpointname").val(point.Name);
        $("#addpointgroup").val(point.GroupName);
        $("#addpointinstalremark").val(point.InstalRemark == null ? "" : point.InstalRemark);
        $("#addpointposition").data("value", point.Position);
        showDialog(250, "Model_AddPoint_Window", 1041);
    });
}

function Save_DeletePointType(id) {
    loaddingshow();
    $.post("/Setting/SaveEdit_DeleteBridgePointType", { BridgeId: $("#BridgeId").val(), pointTypeId: id }, function () {
        //删除对应3d中的传感器
        var deleteids = [];
        var alloldpoints = $("#panel" + id + " ul").find("li");
        for (var ii = 0; ii < alloldpoints.length; ii++) {
            var iid = $(alloldpoints[ii]).find("input[type='hidden']").data("pointid");
            if ($("#ModelShowType").data("showedtype") === "three3d") {
                $.map3DMaker.editPointByPointId(iid);
            } else {
                deleteids.push(iid);
            }
        }
        if (deleteids.length > 0 && pointsMarker !== undefined && pointsMarker !== null) {
            DeleteMapPointMarker(deleteids);
        }

        $("#setpointtypepanel_" + id).remove();
        $("#addpointtype_" + id).show();
        layer.msg('删除成功');
        loaddinghide();
    });
}

var nowshowSectionToMap_Id = "";
var nowshowSectionToMap_Names = "";
function ShowSectionToMap(id) {
    if (nowshowSectionToMap_Id == id) {
        $("#set_section_" + nowshowSectionToMap_Id).removeClass("menu_section_model_hover");
        $.map3DMaker.hideSectionBySectionNames(nowshowSectionToMap_Names);
        nowshowSectionToMap_Id = "";
        nowshowSectionToMap_Names = "";
    } else {
        var positionnames = $("#set_section_" + id).find(".menu_sec_name").data("position");
        if (nowshowSectionToMap_Names != "") {
            $.map3DMaker.hideSectionBySectionNames(nowshowSectionToMap_Names);
        }
        nowshowSectionToMap_Names = positionnames;
        $.map3DMaker.showSectionBySectionNames(positionnames);
        if (nowshowSectionToMap_Id != "") {
            $("#set_section_" + nowshowSectionToMap_Id).removeClass("menu_section_model_hover");
        }
        nowshowSectionToMap_Id = id;
        $("#set_section_" + id).addClass("menu_section_model_hover");
    }
}

var oldSelectedId = 0;
var oldSelectedTypeId = 0;
function SetPointLiSelectedStatus(type, id) {
    $("#set_pointli_" + oldSelectedId).removeClass("menu_section_model_hover");
    oldSelectedId = id;
    $('#set_pointli_' + id).addClass("menu_section_model_hover");
    if (oldSelectedTypeId !== type) {
        $("#panel" + oldSelectedTypeId).collapse("hide");
        oldSelectedTypeId = type;
        $('#panel' + type).collapse("show");
    }

    //定位当前传感器的位置，保证右侧选中传感器能显示
    var alltypesonlis = $('#setpointtypepanel_' + type).parent().find(".addpointtypepanel");
    var alltypesonlilength = 0;
    for (var i = 0; i < alltypesonlis.length; i++) {
        if ($(alltypesonlis[i]).attr("id") != ("setpointtypepanel_" + type)) {
            alltypesonlilength++;
        } else {
            break;
        }
    }
    var alltypesonpointlis = $('#setpointtypepanel_' + type + ' div ul').find("li");
    var alltypesonpointlilength = 0;
    for (var j = 0; j < alltypesonpointlis.length; j++) {
        if ($(alltypesonpointlis[j]).attr("id") != ("set_pointli_" + id)) {
            alltypesonpointlilength++;
        } else {
            break;
        }
    }
    var scrollTopLength = (alltypesonlilength * 58) + (alltypesonpointlilength * 50);
    $('#monitorPoint').parent().parent().scrollTop(scrollTopLength);
}

var isPointLiOnClick = false;
function SelectedPoints_PointType(pointtypeid) {
    setTimeout(function () {
        if (!isPointLiOnClick) {
            if (pointtypeid !== oldSelectedTypeId && oldSelectedTypeId !== 0) {
                //取消原有的展开的 ul 和下的li
                var alloldpoints = $("#panel" + oldSelectedTypeId).find("ul").find("li");
                var alloldids = new Array();
                for (var ii = 0; ii < alloldpoints.length; ii++) {
                    alloldids.push($(alloldpoints[ii]).data("pointid"));
                }
                if ($("#model3d").html() != "") {
                    for (var kk = 0; kk < alloldids.length; kk++) {
                        $.map3DMaker.cancelSelectedPoint(alloldids[kk]);
                    }
                }
                $("#set_pointtype_" + oldSelectedTypeId).find(".menu_sec_model").hide();
                oldSelectedTypeId = pointtypeid;
            }
            var ids = new Array();
            var allpoints = $("#panel" + pointtypeid).find("ul").find("li");
            for (var i = 0; i < allpoints.length; i++) {
                ids.push($(allpoints[i]).find("input[type='hidden']").data("pointid"));
            }
            if ((location.href + "").toLowerCase().indexOf("/setting/set/") > 0 || !$("#model3d").is(":hidden")) {
                if ($("#panel" + pointtypeid).hasClass("in")) {
                    //显示
                    $.map3DMaker.selectedPoint(null, pointtypeid);
                } else {
                    //隐藏
                    //for (var k = 0; k < ids.length; k++) {
                    //    $.map3DMaker.cancelSelectedPoint(ids[k]);
                    //}
                    //隐藏对应传感器li的选中状态
                    $("#panel" + pointtypeid + " ul").find("li").removeClass("menu_section_model_hover");
                    $.map3DMaker.selectedPoint(null, "false");
                }
            }
            isPointLiOnClick = false;
        } else {
            isPointLiOnClick = false;
        }
    }, 500);
}

var isNeedClearNowPoint = false;
function ShowNowTimePointData(id, pointdetailtypeid, showModal, e) {
    //if (e && e.stopPropagation) {
    //    e.stopPropagation();
    //} else {
    //    window.event.cancelBubble = true;
    //}
    isPointLiOnClick = true;
    $("#monitorPoint").find("li").removeClass("menu_section_model_hover");
    $("#panel" + pointdetailtypeid + " ul #set_pointli_" + id).addClass("menu_section_model_hover");
    isNeedClearNowPoint = true;//触发该事件的传感器li 触发时会同时触发 上层 ul 上的li的时间，这里屏蔽处理上层li的事件
    if ((location.href + "").toLowerCase().indexOf("/setting/set/") > 0 || $("#model3d").css("z-index") == 1) {
        setTimeout(function () {
            $.map3DMaker.selectedPoint(id, pointdetailtypeid, 'change', showModal, function () {
                if (showModal) {
                    PostSenorDataWindow(id, pointdetailtypeid);
                };
            });
        }, 10);
        return;
    }
    if (location.href.toLowerCase().indexOf("/home/index") > -1) {
        PostSenorDataWindow(id, pointdetailtypeid);
    }
}

function PostSenorDataWindow(id, typeid) {
    showDragDialog('sensorDataModal');
    if (typeid == undefined || id == undefined) {
        $(".sensorModal-bottom .sensorModal-tool").html("");
        return;
    }
    $.get($("#AnalysisPlatformApiAddress").val().trimEnd('/') + "/api/pointtype/pointanalysisaddress/pointtypeid/" + typeid, function (result) {
        if (result.code === 200) {
            //获取当前组件地址
            var postUrl = $("#SharedAeroiotAppAddress").val().trimEnd('/') + "/view/shared/pointdata/monitorobjectid/" + $("#BridgeId").val() + "/pointtypeid/" + typeid + "/pointid/" + id;
            switch (typeid) {
                case 7://风速风向
                case 9://车流量
                case 11://空间GPS
                case 14://GNSS
                case 16://分享
                case 17://重车
                case 23://水位
                case 24://降雨量
                case 25://深部位移
                case 28://渗流
                case 32://视频图片
                case 33://视频
                case 42://崩塌
                case 43://地声
                case 44://深部位移(测斜仪)
                case 45://地下水位
                case 47://无线倾角
                    postUrl = result.result.dataApiAddress + "/" + result.result.viewApiUrl + "/pointdata/monitorobjectid/" + $("#BridgeId").val() + "/pointid/" + id;
                    break;
                default://通用
                    break;
            }

            $.get(postUrl, function (result) {
                $("#sensorDataModal .modal-content").html(result);
                $("#sensorDataModal .modal-header").on("click", ".icon-close", function () {
                    hideDragDialog();
                });
            });
        }
        else {
            $("#sensorDataModal .modal-content").html('<div class="modal-header addMM-header draghead"><button type="button" class="close addMM-close" data-dismiss="modal" aria-hidden="true"><span class="icon icon-close"></span></button><h6 class="modal-title addMM-title" id="myModalLabel">错误</h6></div><div class="modal-body addMM-body" style="height: 300px;text-align: center;padding-top: 130px;">未能成功加载传感器数据</div>');
            $("#sensorDataModal .modal-header").on("click", ".icon-close", function () {
                hideDragDialog();
            });
        }
    });
}

var videono = 0;
function LoadRealSensorWindowChartData(obj) {
    if (!$(obj).hasClass("refrash")) {
        $(obj).parent().find("a").removeClass("active");
        $(obj).addClass("active");
    }
    $(".realsensorchart").html('<p class="msg"><img src="/content/img/loading.gif"/></p>');
    SetChartRefreshImgStyle($(".sensorModal-tool .refrash"));
    var type = $(obj).data("showminute");
    if ($(obj).hasClass("refrash")) {
        type = $(".sensorModal-tool .active").data("showminute");
    }
    if (type == "real") {
        $('.realsensorchart').removeClass("realsensorvideochart");
        var typeid = $("#realwindow_title").data("pointtypeid");
        var typename = $("#realwindow_title").data("pointtypename");
        var uuid = $("#realwindow_title").data("uuid");
        var url = $("#DataApiAddress").val() + "api/analysis/PointTypeRealSornsorCollectionDataStatistics/bridgeid/" + $("#BridgeId").val() + "/pointid/" + $("#realwindow_title").data("pointid") + "/pointtypeid/" + $("#realwindow_title").data("pointtypeid") + "/showcount/" + 10;
        if (typename === "风速风向") {
            url = $("#DataApiAddress").val() + "api/analysis/fsfx_historyandata/" + $("#BridgeId").val() + "/pointtype/" + $("#realwindow_title").data("pointtypeid") + "/pointids/" + $("#realwindow_title").data("pointid") + "/showminute/" + 10;
        }
        else if (typename === "视频") {
            videono++;
            alert(1111);
            $('.realsensorchart').addClass("realsensorvideochart");
            $(".realvideo_window").empty();
            var pointid = $("#realwindow_title").data("pointid");
            $.post($("#DeviceApiAddress").val() + "api/video/get/address", { uuid: uuid }, function (result) {
                if (result.Code === 200 && JSON.stringify(result.Data) !== "{}") {
                    var vurl = result.Data[uuid];
                    if (vurl === "") {
                        layer.msg("获取视频数据成功，但解析视频URL为空");
                    } else {

                        try {
                            $(".realsensorchart").html("<div class='realvideo_window video-js' id='realvideo_window_" + videono + "'></div>");
                            player = window.player = videojs('realvideo_window_' + videono,
                                {
                                    techOrder: ['flvjs'],
                                    languages: { 'zh-CN': { 'Retry': '重试' } },
                                    sources: [{ src: vurl, type: 'video/x-flv' }],
                                    flvjs: { mediaDataSource: { isLive: true, cors: true, withCredentials: false } },
                                    preload: 'auto',
                                    playbackRates: [0.5, 1, 1.5, 2],
                                    controls: true,
                                    autoplay: true,
                                    notSupportedMessage: '暂不支持播放该媒体',
                                    controlBar: { volumePanel: { inline: false } }
                                }, function () {
                                    var sysDeviceCode = getQueryVariable(vurl, 'stream');
                                    var command = "move";
                                    $('#realvideo_window_' + videono).append(
                                        `<div class="video-control">
                        <div class="video-control-btns">
                            <button class="video-control-btn control-up" onclick="videoControl(this);" data-param="{sys_device_code: ${sysDeviceCode},command: ${command} paras: [{ direction: 2 }]}"></button>
                            <div class="video-control-middle clearfix">
                                <button class="video-control-btn control-left" onclick="videoControl(this);" data-param="{sys_device_code: ${sysDeviceCode},command: ${command} paras: [{ direction: 0}]}"></button>
                                <div class="video-control-scale">
                                    <button class="video-control-btnscale control-enlarge" onclick="videoControl(this);" data-param="{sys_device_code: ${sysDeviceCode},command: ${command} paras: [{ direction: 5}]}"></button>
                                    <button class="video-control-btnscale control-narrow" onclick="videoControl(this);" data-param="{sys_device_code: ${sysDeviceCode},command: ${command} paras: [{ direction: 4}]}"></button>
                                </div>
                                <button class="video-control-btn control-right" onclick="videoControl(this);" data-param="{sys_device_code: ${sysDeviceCode},command: ${command} paras: [{ direction: 1}]}"></button>
                            </div>
                            <button class="video-control-btn control-down" onclick="videoControl(this);" data-param="{sys_device_code: ${sysDeviceCode},command: ${command} paras: [{ direction: 3}]}"></button>
                        </div>
                    </div>
                    <div class="video-control-loading">
                            镜头切换中，请稍后... 
                    </div>`);
                                    this.play();
                                });
                        } catch (e) {
                            console.log("播放视频出现错误：" + e);
                        }
                    }
                } else {
                    layer.msg("未能成功获取视频URL，请稍后再试");
                }
                $(".loadingvideourl").hide();
            });
            return;
        }
        var sensorUnits = setChartInfo(typename);
        $.post(url, function (result) {
            if (result.Code === 200) {
                $('.realsensorchart').removeClass("realsensorvideoimgchart");
                if (typename === "风速风向") {
                    var windData = $.parseJSON(result.Result.ResultDataJsons);
                    WindFunction.InstallWindChart_History($('.realsensorchart'), windData, 60 * 1000, true);
                    return;
                } else {
                    var realhistorydatas = new Array();
                    for (var i = 0; i < result.Result.length; i++) {
                        var realhistorydata = new Object();
                        realhistorydata.name = result.Result[i].Name;
                        realhistorydata.data = new Array();
                        for (var j = 0; j < result.Result[i].Datas.length; j++) {
                            if (typename === "GNSS" || typename === "GPS")
                                realhistorydata.data.push([result.Result[i].Datas[j].TimeStamp * 1000, result.Result[i].Datas[j].Value.toFixed(3) * 1]);
                            else if (typename === "降雨量")
                                realhistorydata.data.push([result.Result[i].Datas[j].TimeStamp * 1000, result.Result[i].Datas[j].Value]);//降雨量加上0.01
                            else
                                realhistorydata.data.push([result.Result[i].Datas[j].TimeStamp * 1000, result.Result[i].Datas[j].Value]);
                        }
                        realhistorydatas.push(realhistorydata);
                    }

                    var realcharttype = 'spline';
                    switch (typename) {
                        case "降雨量":
                            realcharttype = 'column';
                            break;
                        case "水位":
                            realcharttype = 'areaspline';
                            break;
                        case "GNSS":
                        case "GPS":
                            sensorUnits = ["GNSS：mm", "mm"];
                            break;
                        default:
                            break;
                    }
                    $('.realsensorchart').highcharts({
                        chart: {
                            type: realcharttype, animation: Highcharts.svg, marginRight: 110,
                            events: {
                                load: function () {
                                    var chart = this;
                                    var serielist = chart.series;
                                    var windowRealDataSocket = window.WebSocket || window.MozWebSocket;
                                    if (window.windowRealDataSocket != undefined) { window.windowRealDataSocket.close(); }
                                    window.windowRealDataSocket = new windowRealDataSocket($("#WebSocketServerUrl").val() + "?uuid=" + uuid + "_" + typeid);
                                    window.windowRealDataSocket.onmessage = function (evt) {
                                        if (evt.data) {
                                            var point = $.parseJSON(evt.data);
                                            if (point.UUID === uuid) {
                                                SetChartRefreshImgStyle($(".sensorModal-bottom .sensorModal-tool .refrash"));
                                                var time = new Date(point.DateTime);
                                                var timeSpan = time.getTime();
                                                switch (typename) {
                                                    case "GNSS":
                                                    case "GPS":
                                                        for (var i = 0; i < serielist.length; i++) {
                                                            var serie = serielist[i];
                                                            var value = 0;
                                                            if (serie.name.indexOf('_N') > -1) { if (!isNaN(point.X)) { value = (point.X * 100).toFixed(0); } }
                                                            if (serie.name.indexOf('_E') > -1) { if (!isNaN(point.Y)) { value = (point.Y * 100).toFixed(0); } }
                                                            if (serie.name.indexOf('_U') > -1) { if (!isNaN(point.H)) { value = (point.H * 100).toFixed(0); } }
                                                            serie.addPoint([timeSpan, parseFloat(value)], true, true);
                                                        }
                                                        break;
                                                    case "降雨量":
                                                        for (var o = 0; o < serielist.length; o++) {
                                                            var oserie = serielist[o];
                                                            var ovalue = 0;
                                                            if (!isNaN(point.DataValue)) {
                                                                ovalue = parseFloat(point.DataValue).toFixed(2) * 1;
                                                            }
                                                            oserie.addPoint([timeSpan, (ovalue)], true, true);
                                                        }
                                                        break;
                                                    default:
                                                        for (var o = 0; o < serielist.length; o++) {
                                                            var oserie = serielist[o];
                                                            var ovalue = 0;
                                                            if (!isNaN(point.DataValue)) {
                                                                ovalue = parseFloat(point.DataValue).toFixed(2) * 1;
                                                            }
                                                            oserie.addPoint([timeSpan, ovalue], true, true);
                                                        }
                                                        break;
                                                }
                                            }
                                        }
                                    };
                                }
                            }
                        },
                        colors: ['#7FBF7F', '#7F7FFF', '#FF6F10', '#8756D8', '#FF7F7F'],
                        title: { text: '', enabled: false },
                        xAxis: { type: 'datetime', dateTimeLabelFormats: { month: '%y年%m月', day: '%m月%e日', week: '%m月%e日', hour: '%H:%M' }, lineColor: 'red', tickColor: '#222', labels: { style: { color: '#222' } }, tickWidth: 2, tickmarkPlacement: 'on', tickPixelInterval: 100 },
                        yAxis: { title: { text: sensorUnits[0] }, plotLines: [{ value: 0, width: 1, color: '#808080' }] },
                        tooltip: { formatter: function () { var date = new Date(this.x); return "测点:[<b>" + this.series.name + "</b>]<br>时间:[" + date.format("yyyy-MM-dd hh:mm:ss") + "]<br>数据:[" + this.y + " " + sensorUnits[1] + "]"; } },
                        legend: { align: 'right', verticalAlign: 'center', x: 0, y: 0, layout: 'vertical', enabled: true },
                        credits: { enabled: false },
                        exporting: { enabled: false },
                        plotOptions: { areaspline: { fillColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [[0, Highcharts.getOptions().colors[0]], [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]] }, marker: { enabled: false }, lineWidth: 1, states: { hover: { lineWidth: 1 } }, threshold: null } },
                        series: realhistorydatas
                    });
                }
            }
            else { $(".realsensorchart").html('<p class="msg">获取硬件数据失败</p>'); }
        });
    }
    else {
        var typename = $("#realwindow_title").data("pointtypename");
        var url = $("#DataApiAddress").val() + "api/analysis/PointTypeRealSornsorDataStatistics/bridgeid/" + $("#BridgeId").val() + "/pointid/" + $("#realwindow_title").data("pointid") + "/pointtypeid/" + $("#realwindow_title").data("pointtypeid") + "/minute/" + type;
        if (typename == "GNSS" || typename == "GPS") {
            url = $("#DataApiAddress").val() + "api/analysis/regressdata_tominute/" + $("#BridgeId").val() + "/pointtype/" + $("#realwindow_title").data("pointtypeid") + "/pointid/" + $("#realwindow_title").data("pointid") + "/minute/" + type + "/chartdatatype/" + 0;
        }
        else if (typename == "风速风向") {
            url = $("#DataApiAddress").val() + "api/analysis/historyandata/" + $("#BridgeId").val() + "/pointtype/" + $("#realwindow_title").data("pointtypeid") + "/pointids/" + $("#realwindow_title").data("pointid") + "/showminute/" + type;
        }
        $.post(url, function (result) {
            if (result.Code === 200) {
                var datas = result.Result;
                var sensorUnits = setChartInfo(typename);
                var timeFormatUnit = "yyyy-MM-dd hh:mm:ss";
                switch (typename) {
                    case "GNSS":
                    case "GPS":
                        var chartDataStr = result.Result.ResultDataJsons;
                        if (chartDataStr !== "") {
                            var chartData = ($.parseJSON(chartDataStr))[0];
                            if (chartData.length > 0) {
                                $('.realsensorchart').highcharts({
                                    type: 'spline',
                                    colors: ['#7FBF7F', '#7F7FFF', '#FF6F10', '#8756D8', '#FF7F7F'],
                                    title: { text: '', enabled: false },
                                    xAxis: { type: 'datetime', dateTimeLabelFormats: { month: '%y年%m月', day: '%m月%e日', week: '%m月%e日', hour: '%H:%M' }, lineColor: 'red', tickColor: '#222', labels: { style: { color: '#222' } }, tickWidth: 2, tickmarkPlacement: 'on', tickPixelInterval: 100 },
                                    yAxis: { title: { text: sensorUnits[0] }, plotLines: [{ value: 0, width: 1, color: '#808080' }] },
                                    tooltip: { formatter: function () { var date = new Date(this.x); return "测点:[<b>" + this.series.name + "</b>]<br>时间:[" + date.format("yyyy-MM-dd hh:mm:ss") + "]<br>数据:[" + this.y + " " + sensorUnits[1] + "]"; } },
                                    legend: { align: 'right', verticalAlign: 'center', x: 0, y: 0, layout: 'vertical', enabled: true },
                                    credits: { enabled: false },
                                    exporting: { enabled: false },
                                    plotOptions: { spline: { marker: { enabled: false } } },
                                    series: chartData
                                });
                            } else {
                                $(".realsensorchart").html('<p class="msg">该时间段内无数据</p>');
                            }
                        } else {
                            $(".realsensorchart").html('<p class="msg">该时间段内无数据</p>');
                        }
                        break;
                    case "水位":
                        if (datas.length > 0) {
                            var swdatas = new Array();
                            for (var i = 0; i < datas.length; i++) { swdatas.push([datas[i].TimeStamp * 1000, datas[i].PointValue]); }
                            $('.realsensorchart').highcharts({
                                chart: { zoomType: 'x' }, title: { text: '' }, xAxis: { type: 'datetime', dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%m-%d', week: '%m-%d', month: '%Y-%m', year: '%Y' } },
                                tooltip: { formatter: function () { var date = new Date(this.x); return "测点:[<b>" + this.series.name + "</b>]<br>时间:[" + date.format(timeFormatUnit) + "]<br>数据:[" + this.y + " " + sensorUnits[1] + "]"; } },
                                yAxis: { title: { text: sensorUnits[0] } },
                                legend: { enabled: false },
                                colors: ['#7FBF7F', '#7F7FFF', '#FF6F10', '#8756D8', '#FF7F7F'],
                                plotOptions: { areaspline: { fillColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [[0, Highcharts.getOptions().colors[0]], [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]] }, marker: { enabled: false }, lineWidth: 1, states: { hover: { lineWidth: 1 } }, threshold: null } },
                                series: [{ type: 'areaspline', name: $("#realwindow_title").data("pointname"), data: swdatas }]
                            });
                        } else {
                            $(".realsensorchart").html('<p class="msg">该时间段内无数据</p>');
                        }
                        break;
                    case "降雨量":
                        if (datas.length > 0) {
                            var jyldatas = new Array();
                            for (var i = 0; i < datas.length; i++) { jyldatas.push([datas[i].TimeStamp * 1000, datas[i].PointValue]); }
                            $('.realsensorchart').highcharts({
                                chart: { zoomType: 'x' }, title: { text: '' }, xAxis: { type: 'datetime', dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%m-%d', week: '%m-%d', month: '%Y-%m', year: '%Y' } },
                                tooltip: { formatter: function () { var date = new Date(this.x); return "测点:[<b>" + this.series.name + "</b>]<br>时间:[" + date.format(timeFormatUnit) + "]<br>数据:[" + this.y + " " + sensorUnits[1] + "]"; } },
                                yAxis: { title: { text: sensorUnits[0] }, min: 0 },
                                min: 0,
                                legend: { enabled: false },
                                colors: ['#7FBF7F', '#7F7FFF', '#FF6F10', '#8756D8', '#FF7F7F'],
                                plotOptions: { areaspline: { fillColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 0 }, stops: [[0, Highcharts.getOptions().colors[0]], [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]] }, marker: { enabled: false }, lineWidth: 1, states: { hover: { lineWidth: 1 } }, threshold: null } },
                                series: [{ type: 'column', name: $("#realwindow_title").data("pointname"), data: jyldatas }]
                            });
                        } else {
                            $(".realsensorchart").html('<p class="msg">该时间段内无数据</p>');
                        }
                        break;
                    case "风速风向":
                        if (result.Result.ResultDataJsons !== "") {
                            var windData = $.parseJSON(result.Result.ResultDataJsons);
                            WindFunction.InstallWindChart_History($(".realsensorchart"), windData, 60 * 60 * 1000, false);
                        }
                        break;
                    default:
                        if (datas.length > 0) {
                            var otherdatas = new Array();
                            for (var i = 0; i < datas.length; i++) { otherdatas.push([datas[i].TimeStamp * 1000, datas[i].PointValue]); }
                            $('.realsensorchart').highcharts({
                                chart: { zoomType: 'x' }, title: { text: '' }, xAxis: { type: 'datetime', dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%m-%d', week: '%m-%d', month: '%Y-%m', year: '%Y' } },
                                tooltip: { formatter: function () { var date = new Date(this.x); return "测点:[<b>" + this.series.name + "</b>]<br>时间:[" + date.format(timeFormatUnit) + "]<br>数据:[" + this.y + " " + sensorUnits[1] + "]"; } },
                                yAxis: { title: { text: sensorUnits[0] } },
                                colors: ['#7FBF7F', '#7F7FFF', '#FF6F10', '#8756D8', '#FF7F7F'],
                                legend: { enabled: false },
                                series: [{ type: 'spline', name: $("#realwindow_title").data("pointname"), data: otherdatas }]
                            });
                        } else {
                            $(".realsensorchart").html('<p class="msg">该时间段内无数据</p>');
                        }
                        break;
                }
            } else {
                $(".realsensorchart").html('<p class="msg">获取硬件数据失败</p>');
            }
        });
    }
}

function LoadMapModelShowPointFromWarningWindow() {
    var pyname = $(".warningBar-slider .item.active").data("pointtypename");
    var pname = $(".warningBar-slider .item.active").data("pointname");
    var allpmenus = $("#monitorPoint").find(".addpointtypepanel");
    for (var i = 0; i < allpmenus.length; i++) {
        if ($(allpmenus[i]).find("div a span")[0].textContent === pyname) {
            var alllpsmenus = $(allpmenus[i]).find("div ul li");
            for (var j = 0; j < alllpsmenus.length; j++) {
                if ($(alllpsmenus[j]).find(".showtext")[0].textContent === pname) {
                    var pointid = $(alllpsmenus[j]).find(".menu_sec_name").data("pointid"), pointtypeid = $(alllpsmenus[j]).find(".menu_sec_name").data("pointtypeid");
                    $.map3DMaker.selectedPoint(pointid, pointtypeid);
                    break;
                }
            }
            break;
        }
    }
}
function Edit_AddSection() {
    $.post("/Setting/GetAllPoint", { bridgeid: $("#BridgeId").val() }, function (pointsStr) {
        var points = $.parseJSON(pointsStr);
        var htmls = "";
        for (var i = 0; i < points.length; i++) {
            htmls += '<li id="new_section_point_' + points[i].Id + '" data-pointid="' + points[i].Id + '">' +
                '<label type="checkbox" class="checkbox"><input type="checkbox" name="addpointtypefrom" data-pointid="' + points[i].Id + '"/><span>' + points[i].ShowText + '</span></label>' +
                '</li>';
        }
        $("#new_section_points").html(htmls);

        htmls = "";
        $.post("/Setting/GetBridgeModelFiles", { bridgeid: $("#BridgeId").val() }, function (sectionsStr) {
            var sections = $.parseJSON(sectionsStr);
            for (var s = 0; s < sections.length; s++) {
                console.log(sections[s]);
                htmls += '<li><label id="new_sectionposition_point_' + sections[s] + '" class="checkbox" type="checkbox" data-name="' + sections[s] + '" onchange="ShowModelPosition(this);"><input type="checkbox" name="sectionposition" data-name="' + sections[s] + '"/><span>' + sections[s] + '</span></li>';
            }
            $("#new_section_weizhi").html(htmls);
        });
    });
    $("#NowEditSectionId").val("0");
    $("#newsectionname").val("");
    $("#new_section_points input:checkbox").removeAttr("checked");
    showDialog(900, "Model_Addpointsectionwindow");
}


function Edit_AddPointSection() {
    var name = $.trim($("#newsectionname").val());
    if (name == "") {
        layer.alert("结构名称不能为空!");
        return;
    }
    var allmodelposition = $("input[name='sectionposition']:checked");
    if (allmodelposition.length == "" || allmodelposition.length == 0) {
        layer.alert("模型位置未选择!");
        return;
    }
    var modelpositions = "";
    for (var i = 0; i < allmodelposition.length; i++) {
        modelpositions += $(allmodelposition[i]).data("name") + ",";
    }
    modelpositions = modelpositions.substring(0, modelpositions.length - 1);
    var allpoints = $("input[name='addpointtypefrom']:checked");
    //if (allpoints.length == "") {
    //    layer.alert("包含传感器未选择!");
    //    return;
    //}
    var points = "";
    for (var k = 0; k < allpoints.length; k++) {
        points += $(allpoints[k]).data("pointid") + ",";
    }
    points = points.substring(0, points.length - 1);
    $.post("/Setting/SaveSection", {
        bridgeid: $("#BridgeId").val(),
        sectionid: $("#NowEditSectionId").val(),
        pointids: points,
        name: name,
        position: modelpositions
    }, function (result) {
        var status = result.split('|')[0];
        if (status == "False" || status == "false") {
            layer.alert(result.split('|')[1]);
        } else {
            layer.msg("保存成功!");
            var section = $.parseJSON(result);
            if ($("#NowEditSectionId").val() == "0") {
                var htmls = '<li id="set_section_' + section.Id + '" data-id="' + section.Id + '" onclick="ShowSectionToMap(' + section.Id + ')">' +
                    '<i class="ico ico-3D-modal"></i>' +
                    '<input type="hidden" class="menu_sec_name" disabled="disabled" data-sectionid="' + section.Id + '" data-position="' + modelpositions + '" data-weight="0" data-deletetype="section">' +
                    '<span class="sectionnamespan">' + section.Name + '</span>' +
                    '<span class="dropdown">' +
                    '<i class="ico ico-sideBar-more dropdown-toggle fr" data-toggle="dropdown"></i>' +
                    '<ul class="dropdown-menu scroll">' +
                    '<li><a href="javascript:(0);" onclick="EditSectionText(this);">修改</a></li>' +
                    '<li><a href="javascript:(0);" onclick="DeleteSectionMenu(this);">删除</a></li>' +
                    '</ul>' +
                    '</span>' +
                    '</li>';
                //htmls = '<li id="set_section_' + section.Id + '" data-id="' + section.Id + '"><div class="li_con menu_section_model"><i class="icon menu sectionico"></i><input type="hidden" class="menu_sec_name" disabled="disabled" data-sectionid="' + section.Id + '" data-position="' + modelpositions + '" data-deletetype="section"><span class="menu_name">' + section.Name + '</span><span class="icon setting"></span></div></li>';
                $("#set_section_ul").append(htmls);
            } else {
                $("#set_section_" + $("#NowEditSectionId").val() + " .sectionnamespan").text(name);
                $("#set_section_" + $("#NowEditSectionId").val() + " .menu_sec_name").data("position", modelpositions);
            }
            hideDialog();
            loaddinghide();
        }
    });
}

function EditSectionText(sec) {
    var positions = $(sec).parent().parent().parent().parent().find(".menu_sec_name").data("position").split(',');
    var sectionid = $(sec).parent().parent().parent().parent().find(".menu_sec_name").data("sectionid");
    var htmls = "";
    $.post("/Setting/GetAllPoint", { bridgeid: $("#BridgeId").val() }, function (pointsStr) {
        var points = $.parseJSON(pointsStr);
        for (var i = 0; i < points.length; i++) {
            var ischeckedcode = '';
            if (sectionid == points[i].SectionId) {
                ischeckedcode = "checked";
            }
            htmls += '<li id="new_section_point_' + points[i].Id + '" data-pointid="' + points[i].Id + '">' +
                '<label type="checkbox" class="checkbox"><input type="checkbox"' + ischeckedcode + ' name="addpointtypefrom" data-pointid="' + points[i].Id + '"/><span>' + points[i].Name + '</span></label>' +
                '</li>';
        }
        $("#new_section_points").html(htmls);
        $("#NowEditSectionId").val(sectionid);
        $("#newsectionname").val($(sec).parent().parent().parent().parent().find(".sectionnamespan").text());

        htmls = "";
        $.post("/Setting/GetBridgeModelFiles", { bridgeid: $("#BridgeId").val() }, function (sectionsStr) {
            var sections = $.parseJSON(sectionsStr);
            for (var s = 0; s < sections.length; s++) {
                htmls += '<li><label id="new_sectionposition_point_' + sections[s] + '" class="checkbox" type="checkbox" data-name="' + sections[s] + '" onchange="ShowModelPosition(this);"><input type="checkbox" name="sectionposition" data-name="' + sections[s] + '"/><span>' + sections[s] + '</span></li>';
            }
            $("#new_section_weizhi").html(htmls);
            for (var k = 0; k < positions.length; k++) {
                $("#new_sectionposition_point_" + positions[k]).find("input[type='checkbox']").prop("checked", true);
            }

            showDialog(900, "Model_Addpointsectionwindow");

            setTimeout(function () {
                var al = $('input[name="sectionposition"]:checked');
                for (var j = 0; j < al.length; j++) {
                    ShowModelPosition($(al[j]).parent());
                }
                //ShowSectionToMap(sectionid);
            }, 1000);
        });
    });
}

function ShowModelPosition(obj) {
    var positionname = $(obj).find("input[type='checkbox']").data("name");
    if ($(obj).find("input[type='checkbox']").is(':checked')) {
        //选中
        $.map3DMaker.showSectionBySectionName(positionname);
    } else {
        //取消选中
        $.map3DMaker.hideSectionBySectionName(positionname);
    }
}

function DeleteSectionMenu(obj) {
    var sectionid = $(obj).parent().parent().parent().parent().data("id");
    $.post("/Setting/DeleteSection", { bridgeid: $("#BridgeId").val(), sectionid: sectionid }, function () {
        $("#set_section_" + sectionid).remove();
        layer.msg("删除成功");
    });
}

function Edit_AddSectionPointRelationship() {
    $.post("/Setting/GetAllPoint", { bridgeid: $("#BridgeId").val() }, function (pointsStr) {
        var points = $.parseJSON(pointsStr);
        var htmls = "";
        for (var i = 0; i < points.length; i++) {
            var pointtype = "";
            if (points[i].PointType.length > 0)
                pointtype = points[i].PointType[0];

            htmls += '<li>' +
                '<input type="radio" class="son_model_point_radio" name="setpointmodels" onclick="SetModelPointModelsSelected(\'' + points[i].Id + '\',\'' + pointtype + '\',\'' + points[i].Name + '\')"/>' +
                '<input type="text" class="son_model_point" id="son_new_section_point_' + points[i].Id + '" disabled="disabled" value="' + points[i].Name + '"/>' +
                '<span>模型：</span><input type="text" class="son_model_point_models" id="son_new_section_point_' + points[i].Id + '_models" disabled="disabled" data-pointid="' + points[i].Id + '" value="' + (points[i].ModelNames == undefined ? "" : points[i].ModelNames) + '"/></label>' +
                '</li>';
        }
        $("#sonsectionwindowpoints").html(htmls);
        htmls = "";
        $.post("/Setting/GetBridgeModelFiles", { bridgeid: $("#BridgeId").val() }, function (sectionsStr) {
            var sections = $.parseJSON(sectionsStr);
            for (var s = 0; s < sections.length; s++) {
                htmls += '<li><label id="son_new_sectionposition_point_' + sections[s] + '" class="checkbox" type="checkbox" data-name="' + sections[s] + '"><input type="checkbox" name="newsectionposition" data-name="' + sections[s] + '" onchange="SetPointModelsToPoint(this);"/><span>' + sections[s] + '</span></li>';
            }
            $("#sonnewsectionposition").html(htmls);
        });
    });
    $("#sonnewsectionposition input:checkbox").removeAttr("checked");
    showDialog(950, "Model_PointSectionRelationwindow");
}


function Edit_SavePointModelRelation() {
    var allmodelposition = $("input[name='newsectionposition']:checked");
    if (allmodelposition.length == "" || allmodelposition.length == 0) {
        layer.alert("所属子模型未选择!");
        return;
    }
    if ($("#nowsetpointmodels").data("pointid") == "") {
        layer.alert("传感器未选择!");
        return;
    }
    var modelpositions = "";
    for (var i = 0; i < allmodelposition.length; i++) {
        modelpositions += $(allmodelposition[i]).data("name") + ",";
    }

    $.post("/Setting/SavePointModelRelation", { bridgeid: $("#BridgeId").val(), pointid: $("#nowsetpointmodels").data("pointid"), models: modelpositions }, function (result) {
        if (result) {
            layer.msg("保存成功");
            for (var k = 0; k < allmodelposition.length; k++) {
                var name = $(allmodelposition[k]).data("name");
                $.map3DMaker.hideSectionBySectionName(name);
            }
        } else {
            layer.msg(result);
        }
    });
}

function SetModelPointModelsSelected(id, typeid, name) {
    SetModelPointSelected(id, typeid, name);

    //取消选中
    var allmodes = $("input[name='sectionposition']:checked");
    for (var j = 0; j < allmodes.length; j++) {
        $(allmodes[j]).prop("checked", false);
    }
    var namesT = $("#son_new_section_point_" + id + "_models").val();
    if (namesT == "null") {
        $("#son_new_section_point_" + id + "_models").val("");
    }
    $("#nowsetpointmodels").text(name);
    $("#nowsetpointmodels").data("pointid", id);
    var names = namesT.split(',');
    for (var i = 0; i < names.length; i++) {
        var nowname = names[i];
        if (nowname != "") {
            $("#son_new_sectionposition_point_" + nowname).find("input[type='checkbox']").prop("checked", true);
        }
    }
}

function SetModelPointSelected(id, typeid, name) {
    $.map3DMaker.selectedPoint(id, typeid);
    $("#modelnowpoint").text(name);
    $("#modelnowpoint").show();
}


function SetPointModelsToPoint(obj) {
    var name = $(obj).data("name");
    var pointid = $("#nowsetpointmodels").data("pointid");
    if (pointid != "") {
        ShowModelPosition($(obj).parent());
        if ($(obj).is(':checked')) {
            //选中
            $("#son_new_section_point_" + pointid + "_models").val($("#son_new_section_point_" + pointid + "_models").val() + name + ",");
        } else {
            //取消选中
            var value = $("#son_new_section_point_" + pointid + "_models").val();
            value = value.replace(name + ",", "");
            $("#son_new_section_point_" + pointid + "_models").val(value);
        }
    }
}

function EditePointDetail(obj) {
    var pointdetailid = $(obj).parent().parent().data("pointdetailid");
    var pointid = $(obj).parent().parent().data("pointid");
    $("#NowUpdatePointDetailId").val(pointdetailid);
    $("#NowUpdatePointName").val($("#jc_tr_" + pointdetailid + " td:nth-child(1)").text());
    $("#NowUpdatePoint_YellowMaxValue").val($(obj).parent().parent().data("yellowmax"));
    $("#NowUpdatePoint_YellowMinValue").val($(obj).parent().parent().data("yellowmin"));
    $("#NowUpdatePoint_MaxValue").val($(obj).parent().parent().data("max"));
    $("#NowUpdatePoint_MinValue").val($(obj).parent().parent().data("min"));
    $("#NowUpdatePoint_StartValue").val($(obj).parent().parent().data("startvalue"));
    var typeid = $("#jc_tr_" + pointdetailid).data("type");
    $("#NowUpdatePointType").val(typeid);
    if (PointTypePlanHasMaxValueDictionary[typeid] === false) {
        $("#NowUpdatePoint_YellowMinValue").hide();
        $("#NowUpdatePoint_MinValue").hide();
        $(".setpointdetailunitone").hide();
        $("#NowUpdatePoint_YellowMinValue").parent().find(".connectionspan").hide();
        $("#NowUpdatePoint_MinValue").parent().find(".connectionspan").hide();
    } else {
        $("#NowUpdatePoint_YellowMinValue").show();
        $("#NowUpdatePoint_MinValue").show();
        $(".setpointdetailunitone").show();
        $("#NowUpdatePoint_YellowMinValue").parent().find(".connectionspan").show();
        $("#NowUpdatePoint_MinValue").parent().find(".connectionspan").show();
    }
    //处理其他参数
    if (typeid === 25 || typeid === 44 || typeid === 28 || typeid === 34 || typeid === 45) {// 渗流,浸润线,深部位移(测斜仪),地下水位
        $("#NowUpdatePoint_AbsoluteAltitude").val($(".editpointdetailtable").find(".otherparcontent_" + pointid + "_" + pointdetailid).data("absolutealtitude"));
        $("#NowUpdatePoint_HoleDepth").val($(".editpointdetailtable").find(".otherparcontent_" + pointid + "_" + pointdetailid).data("holedepth"));
        if (typeid === 44) {//深部位移(测斜仪)
            $("#NowUpdatePoint_Spaceing").val($(".editpointdetailtable").find(".otherparcontent_" + pointid + "_" + pointdetailid).data("spaceing"));
        }
        if (typeid === 45) {//地下水位
            $("#NowUpdatePoint_AbsoluteAltitude").parent().find(".title").text("孔口绝对海拔").attr("placeholder", "孔口绝对海拔");
            $("#NowUpdatePoint_HoleDepth").parent().find(".title").text("安装深度").attr("placeholder", "安装深度");
        } else {
            $("#NowUpdatePoint_AbsoluteAltitude").parent().find(".title").text("绝对海拔").attr("placeholder", "绝对海拔");
            $("#NowUpdatePoint_HoleDepth").parent().find(".title").text("孔深").attr("placeholder", "孔深");
        }
        $(".ottherpar_" + typeid).show();
    }
    else {
        $(".ottherpar_" + typeid).hide();
    }
    $(".autosetareavaluebtn").show();
    $(".pointdetainbaseinfo").show();
    $("#maxminvaluecurve").hide(200);
}

function DelPointDetail(obj) {
    var data = { bridgeid: $("#BridgeId").val(), pointid: $(obj).parent().parent().data("pointid"), pointDetailId: $(obj).parent().parent().data("pointdetailid") };
    layer.confirm('您确定要删除当前监测值数据吗？', {
        btn: ['确定', '取消']
    }, function () {
        $.post("/Setting/DeletePointDetail", data, function (result) {
            if (result) {
                PostPointDetailTable($(obj).parent().parent().data("pointid"));
                layer.alert("删除成功");
                $(".pointdetainbaseinfo2").hide();
            } else {
                layer.alert("删除失败");
            }
        });
    });
}
function ShowDocView(id) {
    layer.open({
        type: 2,
        title: '文件浏览',
        shadeClose: true,
        shade: 0.8,
        area: ['1200px', '90%'],
        content: id
        //content: '/report/reporthtml?monitorobjectid='+$("#BridgeId").val()+"&id="+id
    });
}
function PostPointDetailTable(pointId) {
    $.post("/Setting/GetPoint", { bridgeid: $("#BridgeId").val(), pointid: pointId }, function (pointstr) {
        var point = $.parseJSON(pointstr);
        $("#editbasepointid").val(pointId);
        $("#editbasepointname").val(point.ShowText);
        $("#editbasepointinstalremark").val(point.InstalRemark == null ? "" : point.InstalRemark);
        $("#editbasepointposition").data("value", point.Position);
        $("#editbasepointgroup").val((point.GroupName == null ? "" : point.GroupName));
        $.ajax({
            type: "POST",
            url: "/Setting/GetPointDetail",
            data: { bridgeid: $("#BridgeId").val(), pointId: pointId },
            success: function (data) {
                var point = $.parseJSON(data.split('|')[0]);
                var pointTypeList = $.parseJSON(data.split('|')[1]);
                var optionStr = "";

                //类型下拉select
                for (var j = 0; j < pointTypeList.length; j++) {
                    optionStr += "<option value='" + pointTypeList[j].Id + "'>" + pointTypeList[j].Name + "</option>";
                }
                $("#NowUpdatePointType").html(optionStr);

                //监测值列表table
                var trStr = "";
                var pointDetail = point.PointDetailList;
                for (var k = 0; k < pointDetail.length; k++) {
                    var yellowmax = pointDetail[k].YellowMaxValue,
                        yellowmin = (pointDetail[k].YellowMinValue == null ? "" : pointDetail[k].YellowMinValue),
                        redmax = pointDetail[k].MaxValue,
                        redmin = (pointDetail[k].MinValue == null ? "" : pointDetail[k].MinValue);
                    var yellowinfo = (yellowmin === "" ? (yellowmax) : (yellowmin + " ~ " + yellowmax));
                    var redinfo = (redmin === "" ? (redmax) : (redmin + " ~ " + redmax));
                    var warningareainfo = "<ul class='warningtablelistinfo'><li class='warningyellow'>" + yellowinfo + "</li><li class='warningred'>" + redinfo + "</li></ul>";
                    var typeName = $("#NowUpdatePointType option[value='" + pointDetail[k].PointType + "']").text();
                    trStr += "<tr id='jc_tr_" + pointDetail[k].Id + "' data-name='" + pointDetail[k].Name + "' data-pointid='" + pointDetail[k].PointId + "' data-pointdetailid='" + pointDetail[k].Id + "' data-type='" + pointDetail[k].PointType + "' data-max='" + pointDetail[k].MaxValue + "' data-min='" + pointDetail[k].MinValue + "' data-yellowmax='" + pointDetail[k].YellowMaxValue + "' data-yellowmin='" + pointDetail[k].YellowMinValue + "' data-roughDayCount='" + pointDetail[k].RoughDayCount + "' data-startvalue='" + pointDetail[k].StartValue + "'>"
                        + "<td style='padding-top: 15px;'>" + pointDetail[k].Name + "</td>"
                        + "<td style='padding-top: 15px;'>" + typeName + "</td>"
                        + "<td>" + warningareainfo + "</td>"
                        + "<td style='padding-top: 15px;'>" + pointDetail[k].StartValue + "</td>"
                        + "<td style='padding-top: 15px;'>" +
                        GetPointDetailOtherParToDataTable(typeName, pointDetail[k])//其他参数
                        + "</td>"
                        + "<td style='padding-top: 15px;'>"
                        + "<a onclick='EditePointDetail(this);' href='javascript:void(0)' title='编辑监测值'><img src='/Content/img/Edit1.png' /></a>&nbsp;&nbsp;&nbsp;&nbsp;"
                        + "<a onclick='DelPointDetail(this);'  href='javascript:void(0)' title='删除监测值'><img src='/Content/img/Delete1.png' /></a>"
                        + "</td>"
                        + "</tr>";
                }
                $(".editpointdetailtable tbody").html(trStr);
            },
            error: function () {
                layer.open({
                    type: 1,
                    title: "传感器监测值配置",
                    skin: 'layui-layer-rim', //加上边框
                    area: ['400px', '250px'], //宽高
                    content: '传感器监测信息加载失败!'
                });
            }
        });
    });
}

function GetPointDetailOtherParToDataTable(typeName, pointDetail) {
    if (typeName === "渗流" || typeName === "浸润线" || typeName === "深部位移(测斜仪)" || typeName == "地下水位") {
        pointDetail.AbsoluteAltitude = pointDetail.AbsoluteAltitude === "" || pointDetail.AbsoluteAltitude === null || pointDetail.AbsoluteAltitude === undefined ? 0 : pointDetail.AbsoluteAltitude;
        pointDetail.HoleDepth = pointDetail.HoleDepth === "" || pointDetail.HoleDepth === null || pointDetail.HoleDepth === undefined ? 0 : pointDetail.HoleDepth;
        var html = "<div class='otherparcontent_" + pointDetail.PointId + "_" + pointDetail.Id + "' data-absolutealtitude='" + pointDetail.AbsoluteAltitude + "' data-holedepth='" + pointDetail.HoleDepth + "' data-spaceing='" + pointDetail.Spaceing + "'>绝对海拔:" + pointDetail.AbsoluteAltitude + "<br/>孔深:" + pointDetail.HoleDepth + "(m)";
        if (typeName == "地下水位") {
            html = "<div class='otherparcontent_" + pointDetail.PointId + "_" + pointDetail.Id + "' data-absolutealtitude='" + pointDetail.AbsoluteAltitude + "' data-holedepth='" + pointDetail.HoleDepth + "' data-spaceing='" + pointDetail.Spaceing + "'>孔口绝对海拔:" + pointDetail.AbsoluteAltitude + "<br/>安装深度:" + pointDetail.HoleDepth + "(m)";
        }
        if (typeName === "深部位移(测斜仪)") {
            html += "<br/>间距:" + pointDetail.Spaceing + "(m)";
        }
        html += "</div>";
        return html;
    }
    return "无";
}

function Edit_SetMonitorPointValue(pointId) {
    var pointName = $("#point_edit_" + pointId).val();
    PostPointDetailTable(pointId, pointName);
    $(".pointdetainbaseinfo2").hide();
    var unit = setChartInfo($("#setpointtypepanel_" + ($("#point_edit_" + pointId).data("pointtypeid"))).data("name"));
    $(".setpointdetailunit").text(unit[1]);
    showDialog(900, "Model_UpdatePointMaxMinValueWindow");
    ChangePointDetailType();
}
function edit_mapPostion(pointid) {
    var x = $("#point_edit_" + pointid).data("mapx"), y = $("#point_edit_" + pointid).data("mapy");
    var lng = $("#BridgeLat").val(), lat = $("#BridgeLng").val();
    showDialog(500, "Model_UpdatePointMapPositionWindow");
    setTimeout(function () {
        var map = new AMap.Map('mapContainer', {
            center: [lng, lat],
            layers: [
                new AMap.TileLayer.Satellite(),
                new AMap.TileLayer.RoadNet()
            ],
            zoom: 16
        });
        if (x != 0 && y != 0) {
            var marker = new AMap.Marker({
                position: new AMap.LngLat(x, y),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                title: "传感器所在位置"
            });
            // 将创建的点标记添加到已有的地图实例：
            map.add(marker);
        };
        //显示区域
        /*var amapeditor = {};
        var mapareaPostion = JSON.parse($("#MapAreaJsons").val());

        showMapArea(mapareaPostion);
        function showMapArea(dataArr) {
            var positionArr = dataArr.data;
            var arr = new Array();//经纬度坐标数组
            for (var i = 0; i < positionArr.length; i++) {
                arr.push(new AMap.LngLat(positionArr[i].lng, positionArr[i].lat));
            };

            amapeditor._polygon = (function () {
                return new AMap.Polygon({
                    map: map,
                    path: arr,
                    strokeColor: "#0000ff",
                    strokeOpacity: 1,
                    strokeWeight: 3,
                    strokeStyle: "dashed",
                    fillColor: "#f5deb3",
                    fillOpacity: 0.35
                });

            })();

            amapeditor._polygonEditor = new AMap.PolyEditor(map, amapeditor._polygon);

        };*/
        map.on('click', function (e) {
            var marker = new AMap.Marker({
                position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                title: "传感器所在位置"
            });
            map.clearMap();
            // 将创建的点标记添加到已有的地图实例：
            map.add(marker);
            var data = {
                bridgeid: $("#BridgeId").val(),
                pointid: pointid,
                x: e.lnglat.getLng(),
                y: e.lnglat.getLat()
            }
            $(".mapPointPostion").data("location", JSON.stringify(data))
        });
    }, 600);

}
function SavePointMapPosition() {
    var data = $(".mapPointPostion").data("location");
    if (!data) return;
    data = JSON.parse(data);
    $(".mapPointPostion").data("location", '');
    $.post("/Setting/SavePointMapPosition", data, function (result) {
        if (!result) {
            layer.msg("传感器地图位置信息保存失败");
        } else {
            layer.msg("保存成功");
        }
    });
}

function SavePointDetail() {
    var pointid = $.trim($("#editbasepointid").val()) * 1;
    var pointDetailId = $("#NowUpdatePointDetailId").val();
    var name = $.trim($("#NowUpdatePointName").val());
    var typeid = $("#NowUpdatePointType").val() * 1;
    var yellowmax = $.trim($("#NowUpdatePoint_YellowMaxValue").val());
    var yellowmin = $.trim($("#NowUpdatePoint_YellowMinValue").val());
    var max = $.trim($("#NowUpdatePoint_MaxValue").val());
    var min = $.trim($("#NowUpdatePoint_MinValue").val());
    var svalue = $.trim($("#NowUpdatePoint_StartValue").val());//初始值
    if (PointTypePlanHasMaxValueDictionary[typeid] == false) {
        min = null;
        yellowmin = null;
    }
    //检查当前类型是否已经存在
    if (pointDetailId == "0") {
        var trs = $(".editpointdetailtable tbody").find("tr");
        for (var i = 0; i < trs.length; i++) {
            if ($(trs[i]).data("name") == name) {
                layer.alert("监测值数据列表中已存在监测值:[" + name + "],不能重复添加");
                return;
            }
        }
    }
    if (name === "" || max === "" || min === "" || svalue === "") {
        layer.alert("参数设置不完整");
        return;
    }
    var data = {
        bridgeid: $("#BridgeId").val(),
        pointid: pointid,
        name: name,
        typeid: typeid,
        pointDetailId: pointDetailId,
        yellowmax: yellowmax,
        yellowmin: yellowmin,
        max: max, min: min,
        svalue: svalue
    };

    if (typeid === 25 || typeid === 44 || typeid === 28 || typeid === 34 || typeid === 45) {//深部位移(测斜仪) 渗流 浸润线
        data.absolutealtitude = $("#NowUpdatePoint_AbsoluteAltitude").val();
        data.holedepth = $("#NowUpdatePoint_HoleDepth").val();
        if (typeid === 44) {
            data.spaceing = $("#NowUpdatePoint_Spaceing").val();
        }
    }
    $.post("/Setting/SavePointDetail", data, function (result) {
        if (result) {
            $("#NowUpdatePointDetailId").val(0);
            PostPointDetailTable(pointid, name);
            ClearPointDetail();
            $(".pointdetainbaseinfo2").hide();
            layer.msg("保存成功");
        } else {
            layer.alert("保存失败");
        }
    });
}
function ClearPointDetail() {
    $("#NowUpdatePointDetailId").val(0);
    $("#NowUpdatePointName").val("");
    $("#NowUpdatePoint_YellowMaxValue").val("");
    $("#NowUpdatePoint_YellowMinValue").val("");
    $("#NowUpdatePoint_MaxValue").val("");
    $("#NowUpdatePoint_MinValue").val("");
    $("#NowUpdatePoint_StartValue").val("");
    $("#NowUpdatePoint_RoughMultipleValue").val("");
    $("#maxminvaluecurve").hide();
    $("#DevicePointsSelect").html("");
    $("[name='pointdetaildatafromtype']").attr("checked", false);
    ChangePointDetailType();
    $(".pointdetainbaseinfo").show();
}
function ChangePointDetailType() {
    var ntype = $("#NowUpdatePointType").val();
    if (PointTypePlanHasMaxValueDictionary[ntype]) {
        $("#nowUpdatePointDetailHasMinValueSpan").show();
        $("#NowUpdatePoint_YellowMinValue").data("HasMinValue", true);
        $("#NowUpdatePoint_MinValue").data("HasMinValue", true);
    }
    else {
        $("#nowUpdatePointDetailHasMinValueSpan").hide();
        $("#NowUpdatePoint_YellowMinValue").data("HasMinValue", false);
        $("#NowUpdatePoint_MinValue").data("HasMinValue", false);
    }
    $("#NowUpdatePoint_YellowMinValue").val("");
    $("#NowUpdatePoint_YellowMaxValue").val("");
    $("#NowUpdatePoint_MinValue").val("");
    $("#NowUpdatePoint_MaxValue").val("");

    if (PointTypePlanHasMaxValueDictionary[ntype] == false) {
        $("#NowUpdatePoint_YellowMinValue").hide();
        $("#NowUpdatePoint_YellowMinValue").parent().find(".connectionspan").hide();
        $("#NowUpdatePoint_MinValue").hide();
        $("#NowUpdatePoint_MinValue").parent().find(".connectionspan").hide();
    } else {
        $("#NowUpdatePoint_YellowMinValue").show();
        $("#NowUpdatePoint_MinValue").show();
        $("#NowUpdatePoint_YellowMinValue").parent().find(".connectionspan").show();
        $("#NowUpdatePoint_MinValue").parent().find(".connectionspan").show();
    }

    $("[name='pointdetaildatafromtype']").attr("checked", false);
    $("#DevicePointsSelect").html("");
}
function Edit_UpdatePointName(obj) {
    $(obj).parent().parent().parent().parent().find(".updatepointnameshowtext").show().focus();
    $(obj).parent().parent().parent().parent().find(".showtext").hide();
    $(obj).parent().parent().parent().parent().find(".dropdown").hide();
    $(obj).parent().parent().parent().hide();
    enterEventInput = $(obj).parent().parent().parent().parent().find(".updatepointnameshowtext");
}

function SaveEditPointName(obj) {
    var id = $(obj).parent().find(".menu_sec_name").data("pointid");
    var value = $.trim($(obj).val());
    if (value === "") {
        layer.msg("名称不能为空");
        return;
    }

    $.post("/Setting/SaveEdit_BridgePoint", { bridgeid: $("#BridgeId").val(), pointid: id, pointvalue: value }, function (pointStr) {
        $(obj).hide();
        $(obj).parent().find(".showtext").text(value);
        $(obj).parent().find(".showtext").show();
        $(obj).parent().find(".dropdown").show();
        var pointTypes = $.parseJSON(pointStr).PointType;
        for (var k = 0; k < pointTypes.length; k++) {
            $('#panel' + pointTypes[k] + ' ul #set_pointli_' + id + " .menu_sec_name").val(value);
            $('#panel' + pointTypes[k] + ' ul #set_pointli_' + id + " .showtext").text(value);
        }
        layer.msg("修改成功");
        if ($("#ModelShowType").data("showedtype") == "three3d") {
            $.map3DMaker.ChangeScenePointName(id, value);
        } else {
            MapModelResetPointName(id, value);
        }
    });
}

function GetAnalysisWindowFiterTimes(valuetoid, type, event) {
    var ntime = new Date();
    if (type == 'd') {
        var dstart = ntime.format("MM/dd/yyyy");
        var dend = ntime.format("MM/dd/yyyy");
        $("#" + valuetoid).val(dstart + " - " + dend);
    } else if (type == 'w') {
        var wstart = new Date(ntime.getTime() + (24 * 60 * 60 * -6 * 1000)).format("MM/dd/yyyy");
        var wend = ntime.format("MM/dd/yyyy");
        $("#" + valuetoid).val(wstart + ' - ' + wend);
    } else if (type == 'm') {
        var mstart = new Date(ntime.getTime() + (24 * 60 * 60 * -30 * 1000)).format("MM/dd/yyyy");
        var mend = ntime.format("MM/dd/yyyy");
        $("#" + valuetoid).val(mstart + ' - ' + mend);
    }
    eval(event);
}


function showMonitorRuleTarget() {
    var bridgeId = $("#BridgeId").val();
    $.post("/Setting/GetMonitorRule", { bridgeid: bridgeId }, function (result) {
        var oldMonitorRules = $.parseJSON(result);
        showDialog(820, "Model_UpdateMonitorRuleWindow");
        var htmls = "";
        for (var i = 0; i < oldMonitorRules.length; i++) {
            htmls += "<tr>" +
                "<td style='text-align:center'><input type=\"checkbox\" name=\"waringcc\" data-ruleid=\"" + oldMonitorRules[i].Id + "\" " + oldMonitorRules[i].IsChecked + "/></td>" +
                "<td>" + oldMonitorRules[i].MonitorTypeName + "</td>" +
                "<td>" + oldMonitorRules[i].Notes + "</td>" +
                "</tr>";
        }
        $("#monitorrulebody").html(htmls);
    });
}

function SaveMonitorRuleConfig() {
    var cclist = {};
    var cc = $("#monitorrulebody input[type='checkbox'][name='waringcc']:checked");
    cc.each(function (i) {
        cclist[i] = $(this).data('ruleid');
    });
    $.post("/Setting/UpdateBridgeMonitorRuleConfig", { bridgeid: $("#BridgeId").val(), "ids": cclist }, function (result) {
        if (result) {
            layer.msg('保存成功!');
            setTimeout(function () {
                hideDialog();
                loaddinghide();
                layer.closeAll();
            }, 2000);
        } else {
            layer.alert("保存失败 !");
        }
    });
}

function showAlgorithmSetting() {
    showDialog(900, "Model_updateAlgorithmWindow");
    LoadAlgorithm_Data();
}
function LoadAlgorithm_Data() {
    var a_type = 2;//默认为 层次分析法 //$('#nowalgorithmtype').val();
    loaddingshow();
    $("#sectionweightbody").html("");
    var sectionhtmls = "";
    var pointhtmls = "";
    $.post("/Setting/GetAlgorithmSectionParameter", { bridgeid: $("#BridgeId").val(), algorithmtype: a_type }, function (result) {
        var sectionlis = $.parseJSON(result);

        $.post("/Setting/GetAlgorithmParameter", { bridgeid: $("#BridgeId").val(), algorithmtype: a_type }, function (result) {
            if (result.indexOf("ERROR:") > -1) {
                layer.alert(result);
                loaddinghide();
                return;
            }

            var pointsdatas = $.parseJSON(result);
            for (var i = 0; i < sectionlis.length; i++) {

                for (var j = 0; j < pointsdatas.length; j++) {
                    if (pointsdatas[j].Section == sectionlis[i].Name) {
                        pointhtmls += "<tr>" +
                            "<td>" + sectionlis[i].Name + "</td>" +
                            "<td><input readonly type='text' value='" + pointsdatas[j].PointName + "'/></td>" +
                            "<td><input readonly type='text' value='" + pointsdatas[j].PointTypeCn + "'/></td>" +
                            "<td><input disabled name='p_new_" + a_type + "_startvalue_" + pointsdatas[j].PointName + "' type='text' value='" + (pointsdatas[j].StartValue == null ? "" : pointsdatas[j].StartValue) + "'/></td>" +
                            "<td><input name='p_new_" + a_type + "_minsvalue_" + pointsdatas[j].PointName + "' type='text' value='" + (pointsdatas[j].MinSValue == null ? "" : pointsdatas[j].MinSValue) + "' " + (pointsdatas[j].MinSValue == null ? "disabled" : "") + "/></td>" +
                            "<td><input name='p_new_" + a_type + "_mingvalue_" + pointsdatas[j].PointName + "' type='text' value='" + (pointsdatas[j].MinGValue == null ? "" : pointsdatas[j].MinGValue) + "' " + (pointsdatas[j].MinGValue == null ? "disabled" : "") + "/></td>" +
                            "<td><input name='p_new_" + a_type + "_maxgvalue_" + pointsdatas[j].PointName + "' type='text' value='" + pointsdatas[j].MaxGValue + "'/></td>" +
                            "<td><input name='p_new_" + a_type + "_maxsvalue_" + pointsdatas[j].PointName + "' type='text' value='" + pointsdatas[j].MaxSValue + "'/></td>" +
                            "<td><input name='p_new_" + a_type + "_weight_" + pointsdatas[j].PointName + "' type='text' value='" + pointsdatas[j].Weights + "'/></td>" +
                            "</tr>";
                    }
                }

                sectionhtmls += "<tr>" +
                    "<td><input readonly type='text' value='" + sectionlis[i].Id + "'/></td>" +
                    "<td><input readonly type='text' value='" + sectionlis[i].Name + "'/></td>" +
                    "<td><input type='text' name='section_" + sectionlis[i].Id + "_weight' value='" + sectionlis[i].Weight + "'/></td>" +
                    "</tr>";
            }
            $("#sectionweightbody").html(sectionhtmls);
            $("#pointweightbody").html(pointhtmls);
            loaddinghide();
        });
    });
}

function SaveAlgorithm() {
    $.post("/Setting/SaveAlgorithm", $("#Model_updateAlgorithmWindow").serialize(), function (result) {
        if (result == "") {
            layer.confirm('保存成功! 配置参数将在您确认 [发布] 后才会生效 !', {
                closeBtn: 0,
                btn: ['确定']
            }, function () {
                $("#algorithmtbody_1").html("");
                $("#algorithmtbody_2").html("");
                $("#sectionweightbody").html("");
                hideDialog();
                loaddinghide();
                layer.closeAll();
            });
        } else {
            layer.alert("保存失败 !" + result);
        }
    });
}
function setrightshowwindowtype(windowtype) {
    if (windowtype == 1) {
        //概况
        $.map3DMaker.hideSelectedPoint();
    } else if (windowtype == 2) {
        //监测点
        $.map3DMaker.setIsResetPointSence();
    } else if (windowtype == 3) {
        //子结构
        $.map3DMaker.setIsResetPointSence();
        $.map3DMaker.hideSelectedPoint();
    } else {
        //日常巡检
        $.map3DMaker.showSpectionData();
        $.map3DMaker.hideSelectedPoint();
    }
}

function ShowSpectionData(id) {
    //LoadSpectionNewDataPartialData(id);
}

function createrelitutable(min, max, type) {
    var str = "";
    if (type == "wendu") {
        str = GenerateGradientColor(min, max, 20);
    }
    else if (type == "yingbian") {
        str = GenerateGradientColor(min, max, 20);
    }
    $("#relitutable").show();
    $("#relitutable").html(str);
}

var ReLiColorArrary;//当前类型热力图色值
var ReLiColorOneAddValue;
function GenerateGradientColor(min, max, count) {
    var itemAddCount = max - min;//最大最小差值
    ReLiColorOneAddValue = itemAddCount / count; //每个阶梯的差值
    var liItems = new Array();
    var result = "";

    var setcount = parseInt(count / 3);
    var gradient1 = new gradientColor('#0000FF', '#008000', setcount);//蓝到绿
    var gradient2 = new gradientColor('#008000', '#FFFF00', (count - (setcount * 3) > 0) ? setcount + 1 : setcount);//绿到黄
    var gradient3 = new gradientColor('#FFFF00', '#FF0000', (count - (setcount * 3 + 1) > 0) ? setcount + 1 : setcount);//黄到红
    var startNum = 0;
    for (var i = 0; i < gradient1.length; i++) {//蓝到绿
        var nowItemValuei = (min + ReLiColorOneAddValue * startNum).toFixed(2);
        var nowItemColorStri = gradient1[i].split(',');
        liItems.push({ key: nowItemValuei, r: parseFloat(nowItemColorStri[0]), g: parseFloat(nowItemColorStri[1]), b: parseFloat(nowItemColorStri[2]) });
        result += '<div style="width: 5px;background-color:rgb(' + gradient1[i] + ')">' + nowItemValuei + '</div>';
        startNum++;
    }
    for (var j = 0; j < gradient2.length; j++) {//绿到黄
        var nowItemValuej = (min + ReLiColorOneAddValue * startNum).toFixed(2);
        var nowItemColorStrj = gradient2[j].split(',');
        liItems.push({ key: nowItemValuej, r: parseFloat(nowItemColorStrj[0]), g: parseFloat(nowItemColorStrj[1]), b: parseFloat(nowItemColorStrj[2]) });
        result += '<div style="width: 5px;background-color:rgb(' + gradient2[j] + ')">' + nowItemValuej + '</div>';
        startNum++;
    }
    for (var k = 0; k < gradient3.length; k++) {//黄到红
        var nowItemValuek = (min + ReLiColorOneAddValue * startNum).toFixed(2);
        var nowItemColorStrk = gradient3[k].split(',');
        liItems.push({ key: nowItemValuek, r: parseFloat(nowItemColorStrk[0]), g: parseFloat(nowItemColorStrk[1]), b: parseFloat(nowItemColorStrk[2]) });
        result += '<div style="width: 5px;background-color:rgb(' + gradient3[k] + ')">' + nowItemValuek + '</div>';
        startNum++;
    }

    ReLiColorArrary = liItems;
    return result;
}

/*
  // startColor：开始颜色hex
  // endColor：结束颜色hex
  // step:几个阶级（几步）
  */
function gradientColor(startColor, endColor, step) {
    var startRGB = this.colorRgb(startColor);//转换为rgb数组模式
    var startR = startRGB[0];
    var startG = startRGB[1];
    var startB = startRGB[2];

    var endRGB = this.colorRgb(endColor);
    var endR = endRGB[0];
    var endG = endRGB[1];
    var endB = endRGB[2];

    var sR = (endR - startR) / step;//总差值
    var sG = (endG - startG) / step;
    var sB = (endB - startB) / step;

    var colorArr = [];
    for (var i = 0; i < step; i++) {
        //计算每一步的hex值
        var hex = this.colorHex(parseInt((sR * i + startR)) + ',' + parseInt((sG * i + startG)) + ',' + parseInt((sB * i + startB)));
        colorArr.push(hex);
    }
    return colorArr;
}

// 将hex表示方式转换为rgb表示方式(这里返回rgb数组模式)
gradientColor.prototype.colorRgb = function (sColor) {
    var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    var sColor = sColor.toLowerCase();
    if (sColor && reg.test(sColor)) {
        if (sColor.length === 4) {
            var sColorNew = "#";
            for (var i = 1; i < 4; i += 1) {
                sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
            }
            sColor = sColorNew;
        }
        //处理六位的颜色值
        var sColorChange = [];
        for (var i = 1; i < 7; i += 2) {
            sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
        }
        return sColorChange;
    } else {
        return sColor;
    }
};

function getReLiColorFromKey(key) {
    //等值判断
    for (var i = 0; i < ReLiColorArrary.length; i++) {
        if (key == ReLiColorArrary[i].key) {
            return "rgb(" + ReLiColorArrary[i].r + "," + ReLiColorArrary[i].g + "," + ReLiColorArrary[i].b + ")";
        }
    }
    //区间判断
    for (var j = 1; j < ReLiColorArrary.length + 1; j++) {
        if (ReLiColorArrary[j] != undefined) {
            if (key > ReLiColorArrary[j - 1].key && key < ReLiColorArrary[j].key) {
                var r = parseInt((ReLiColorArrary[j - 1].r + ReLiColorArrary[j].r) / 2);
                var g = parseInt((ReLiColorArrary[j - 1].g + ReLiColorArrary[j].g) / 2);
                var b = parseInt((ReLiColorArrary[j - 1].b + ReLiColorArrary[j].b) / 2);
                return "rgb(" + r + "," + g + "," + b + ")";
            }
        } else {
            if (key > ReLiColorArrary[j - 1].key) {
                var r1 = parseInt(ReLiColorArrary[j - 1].r + (ReLiColorOneAddValue / 2));
                var g1 = parseInt(ReLiColorArrary[j - 1].g + (ReLiColorOneAddValue / 2));
                var b1 = parseInt(ReLiColorArrary[j - 1].b + (ReLiColorOneAddValue / 2));
                return "rgb(" + r1 + "," + g1 + "," + b1 + ")";
            }
        }
    }
    return "";
}
// 将rgb表示方式转换为hex表示方式
gradientColor.prototype.colorHex = function (rgb) {
    var _this = rgb;
    var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    if (/^(rgb|RGB)/.test(_this)) {
        var aColor = _this.replace(/(?:(|)|rgb|RGB)*/g, "").split(",");
        var strHex = "#";
        for (var i = 0; i < aColor.length; i++) {
            var hex = Number(aColor[i]).toString(16);
            hex = hex < 10 ? 0 + '' + hex : hex;// 保证每个rgb的值为2位
            if (hex === "0") {
                hex += hex;
            }
            strHex += hex;
        }
        if (strHex.length !== 7) {
            strHex = _this;
        }
        return strHex;
    } else if (reg.test(_this)) {
        var aNum = _this.replace(/#/, "").split("");
        if (aNum.length === 6) {
            return _this;
        } else if (aNum.length === 3) {
            var numHex = "#";
            for (var i = 0; i < aNum.length; i += 1) {
                numHex += (aNum[i] + aNum[i]);
            }
            return numHex;
        }
    } else {
        return _this;
    }
}

function LoadPointTypeOverviewDetailRealData(pointtypeid, oldinfos) {
    $("#realdatapointtype_" + pointtypeid).find(".overviewvalue label").html("<img src='/content/img/loading.gif'/>");
    var infos = $("#realdatapointtype_" + pointtypeid).data("realinfo");
    if (infos == undefined) {
        $("#realdatapointtype_" + pointtypeid).data("realinfo", oldinfos);
        infos = oldinfos;
    }

    var statisticsarea = infos == null || infos.StatisticsArea == undefined ? 0 : infos.StatisticsArea;
    var statisticstype = infos == null || infos.StatisticsType == undefined ? 0 : infos.StatisticsType;
    var pointids = "";
    if (infos == null || infos.PointIds == null) {
        console.log('右侧传感器类型统计设置未完成,加载数据有错!');
        return;
    }
    for (var i = 0; i < infos.PointIds.length; i++) {
        pointids += infos.PointIds[i] + ",";
    }
    pointids = pointids == "" ? "," : pointids;
    $.ajax({
        url: $("#DataApiAddress").val() + "api/data/windowdata/GetPointTypeRealOverviewData/" + $("#BridgeId").val() + "/" + pointtypeid + "/" + pointids + "/" + statisticsarea + "/" + statisticstype,
        success: function (datas) {
            loaddinghide();
            if (datas.Code == 200) {
                var data = datas.Result;
                $("#realdatapointtype_" + pointtypeid).find(".overviewvalue").data("overviewpointsvalue", data.OverviewPointOverviewData);
                $("#realdatapointtype_" + pointtypeid).find(".overviewvalue").data("statisticstype", statisticstype);
                $("#realdatapointtype_" + pointtypeid).find(".overviewvalue").data("pointtype", pointtypeid);
                $("#realdatapointtype_" + pointtypeid).find(".typeoverviews").find(".typeoverviewspoints").html("");
                if ($("#realdatapointtype_" + pointtypeid).find("span").eq(0).text() == "GNSS") {
                    //GNSS单独处理
                    var html = "X:" + data.BD_E + "mm</br>Y:" + data.BD_N + "mm</br>H:" + data.BD_U + "mm</br>";
                    $("#realdatapointtype_" + pointtypeid).find(".overviewvalue").html(html);
                } if ($("#realdatapointtype_" + pointtypeid).find("span").eq(0).text() == "风速风向") {
                    //风速风向单独处理
                    var html = "风速:" + data.FS + "m/s</br>风向:" + data.FXCn + "°</br>";
                    $("#realdatapointtype_" + pointtypeid).find(".overviewvalue").html(html);
                } else {
                    if (data != "null" && data != null && data.OverviewData != null && data.OverviewData != "null") {
                        $("#realdatapointtype_" + pointtypeid).find(".overviewvalue label").text(data.OverviewData);
                    } else {
                        $("#realdatapointtype_" + pointtypeid).find(".overviewvalue label").text("--");
                    }
                }
            }
        },
        error: function (msg) {
            $("#realdatapointtype_" + pointtypeid).find(".overviewvalue label").text("--");
            loaddinghide();
        }
    });
}

function WebScoketPointTypeOverviewDetailRealData() {
    var url = $("#webSocketServerUrl").val() + "?uuid=" + $("#BridgeId").val();
    var websocket = new WebSocket(url);
    websocket.onopen = function (evt) {
    };
    websocket.onclose = function (evt) {
    };
    websocket.onmessage = function (evt) {
        var dataArray = evt.data.split("}{");
        for (var i = 0; i < dataArray.length; i++) {
            var dataStr = dataArray[i];
            if (i < dataArray.Length - 1) {
                dataStr = dataStr + "}";
            }
            if (i != 0) {
                dataStr = "{" + dataStr;
            }
            var datas = $.parseJSON(dataStr);
            if (datas.Code === 200) {
                var data = datas.Result;
                if ($("#realdatapointtype_" + data.PointTypeId).find("span").eq(0).text() == "GNSS") {
                    //GNSS单独处理
                    var html = "E:" + data.BD_E + "mm</br>N:" + data.BD_N + "mm</br>U:" + data.BD_U + "mm</br>";
                    $("#realdatapointtype_" + data.PointTypeId).find(".overviewvalue").html(html);
                } else {
                    if (data != "null" && data != null && data.PointTypeId != null && data.PointTypeId != "null") {
                        var pointTypeId = data.PointTypeId;
                        if (data != "null" && data != null && data.OverviewData != null && data.OverviewData != "null") {
                            $("#realdatapointtype_" + pointTypeId).find(".overviewvalue label").text(data.OverviewData);
                        } else {
                            $("#realdatapointtype_" + pointTypeId).find(".overviewvalue label").text("--");
                        }
                    }
                }
            }
        }
    };
    websocket.onerror = function (evt) {
    };

}

function pointdatafromtypeChange(showid) {
    if (showid == 0) {
        $("#pointdatafromtypecontent_1").hide();
    } else {
        $("#pointdatafromtypecontent_0").hide();
    }
    $("#pointdatafromtypecontent_" + showid).show();
}

function InstailSystemSettingContent(showid) {
    if ($("#systemsetting_menu").html() == "") {
        var headhtmls = '';
        var alls = $("#settingmenus ul li");
        for (var i = 0; i < alls.length; i++) {
            var id = $(alls[i]).data("functionid");
            var name = $(alls[i]).data("functionname");
            headhtmls += '<span id="systemsetting_m_' + id + '" class="tab-item" data-functionid="' + id + '" data-functionname="' + name + '" data-tab="systemsettingtab_' + id + '" onclick="ShowSystemSetting_Data(' + id + ')">' + name + '</span>';
        }
        headhtmls += '<span id="systemsetting_m_warningmsg" class="tab-item" data-functionid="warningmsg"  data-functionname="预警信息设置" data-tab="systemsettingtab_warningmsg" onclick="ShowSystemSetting_WarningData()">预警信息设置</span>';
        $("#systemsetting_menu").html(headhtmls);
    }
    $("#systemsetting_menu span").removeClass("active");
    $("#systemsetting_m_" + showid).addClass("active");
    $(".systemsettingtab").hide();
    $(".systemsettingtab_" + showid).show();
    ShowSystemSetting_Data(showid);
}

function ShowSystemSetting_Data(id) {
    if (id === 7) {//角色信息列表
        LoadSystemSetting_RoleInfo_Data(1);
    } else if (id === 8) {//部门信息列表
        LoadSystemSetting_DepartmentInfo_Data(1);
    } else if (id === 9) {//用户信息列表
        LoadSystemSetting_UserInfo_Data(1);
    } else if (id === 10) {//权限信息列表
        LoadSystemSetting_Authorizes_Data();
    } else if (id === 21) {//实时数据信息列表
        LoadSystemSetting_RealDataSetting_Data(0);
    } else if (id === 23) {//基本信息设置
        LoadSystemSetting_BaseInfoSet_Data();
    }
}

function LoadSystemSetting_BaseInfoSet_Data() {
    $.get($("#DataApiAddress").val() + "api/bridges/getbridgebaseinfo/" + $("#BridgeId").val(), {}, function (result) {
        if (result.Code == 200) {
            console.log(result.Result);
            SetBandingBaseInfo(result.Result);
        } else {
            alert(result.Message);
        }
    });
}
function ShowSelectMap(x, y, line) {
    showSelectMapIndex = layer.open({
        id: 'mapselectiframe',
        type: 2,
        title: '地理位置选择',
        shadeClose: true,
        shade: 0.8,
        area: ['820px', '560px'],
        content: '/Setting/MapPartial?x=' + x + '&y=' + y + '&line' + line
    });
}

function ShowSetMapCenterPartial() {
    showSetMapCenterMapIndex = layer.open({
        id: 'mapselectiframe',
        type: 2,
        title: '地图中心点选择',
        shadeClose: true,
        shade: 0.8,
        area: ['820px', '560px'],
        content: '/Setting/Set_MapCenterPartial'
    });
}

function CloseMapSelectWindowTest() {
    layer.close(showSelectMapIndex);
    //$("#base_position").val( x + "," + y);
    //$("#setselectmap").data("x", x);
    //$("#setselectmap").data("y", y);
}
function CloseSetMapCenterWindow() {
    layer.close(showSetMapCenterMapIndex);
    ResetChangeMapModel();
}

function SetBandingBaseInfo(data) {
    if (data.BaseInfo.Photo != "") {
        $("#base_photo").val(data.BaseInfo.Photo);
        $("#base_photo").parent("label").css("background-image", "url('" + data.BaseInfo.Photo + "')");
    }
    $("#base_positionremark").val(data.BaseInfo.PositionRemark);
    $("#base_summary").text(data.BaseInfo.Summary);
    if (data.BaseInfo.Position.length == 0) {
        $("#base_position").val("");
    }
    else {
        $("#base_position").val(data.BaseInfo.Position[0] + ',' + data.BaseInfo.Position[1]);
    }
    $("#base_slopetype").val(data.BaseInfo.SlopeType);
    $("#base_yinhuandianleixing").val(data.BaseInfo.YinHuanDianLeiXing);
    $("#base_xianqingdengji").val(data.BaseInfo.XianQingDengJi);
    $("#base_youfayinsu").val(data.BaseInfo.YouFaYinSu);
    $("#base_dizhi").val(data.BaseInfo.DiZhi);
    $("#base_jiegou").val(data.BaseInfo.JieGou);
    $("#base_mianji").val(data.BaseInfo.MianJi);
    $("#base_bagao").val(data.BaseInfo.BaGao);
    $("#base_monitorabsoluteheight").val(data.BaseInfo.MonitorAbsoluteHeight);

    $("#base_yezhuunit").val(data.BaseInfo.yezhuunit);
    $("#base_yezhuphone").val(data.BaseInfo.yezhuphone);
    $("#base_monitorstime").val(data.BaseInfo.monitorstime);

    $('#upload_bridgeimg_btn').uploadify({
        'buttonText': "",
        'swf': '/content/uploadify/uploadify.swf', //设置上传组件uploadify.swf的路径
        'uploader': '/FileUpload/Upload/', //设置上传的Url接口
        'cancelImg': '/content/uploadify/cancel.png',
        'removeCompleted': true,
        'hideButton': true,
        'auto': true,
        'multi': true,
        'wmode': 'transparent',
        'uploadLimit': 99,
        'simUploadLimit': 99,
        'fileTypeDesc': '图片格式:*.jpg;*.gif;*.png;*.bmp',
        'fileTypeExts':'*.jpg;*.gif;*.png;*.bmp',
        'onUploadStart': function (file) {
            $("#upload_bridgeimg_btn").uploadify("settings", "formData", { type: "", bridgeid: $('#BridgeId').val(), modelType: "" });
        },
        'onQueueComplete': function (queueData) { },
        'onCancel': function (file) { },
        'onUploadSuccess': function (file, resultdata, responese) {
            try {
                var filedata = $.parseJSON(resultdata);
                if (resultdata != '[]' && filedata != null) {
                    var url = "/" + filedata.path;
                    $("#base_photo").val(url);
                    $("#base_photo").parent("label").css("background-image", "url('" + url + "')");
                }
            } catch (e) {
                console.log("ERROR:" + e);
            }
            
        }
    });
}
function isNumber(val) {
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
        return true;
    } else {
        return false;
    }
}
function SaveDetailBaseInfo() {
    var base_yezhuunit = $.trim($("#base_yezhuunit").val());
    var base_yezhuphone = $.trim($("#base_yezhuphone").val());
    var base_monitorstime = $.trim($("#base_monitorstime").val());
    var subdata = {
        bridgeid: $("#BridgeId").val(),
        photo: $("#base_photo").val(),
        position: $.trim($("#base_position").val()),
        summary: $("#base_summary").val(),
        slopetype: $.trim($("#base_slopetype").val()),
        yinhuandianleixing: $.trim($("#base_yinhuandianleixing").val()),
        xianqingdengji: $.trim($("#base_xianqingdengji").val()),
        youfayinsu: $.trim($("#base_youfayinsu").val()),
        positionremark: $.trim($("#base_positionremark").val()),
        dizhi: $.trim($("#base_dizhi").val()),
        jiegou: $.trim($("#base_jiegou").val()),
        mianji: $.trim($("#base_mianji").val()),
        monitorabsoluteheight: $.trim($("#base_monitorabsoluteheight").val()) == "" ? 0 : $.trim($("#base_monitorabsoluteheight").val()) * 1,
        bagao: $.trim($("#base_bagao").val()) == "" ? 0 : $.trim($("#base_bagao").val()) * 1,

        yezhuunit: base_yezhuunit,
        yezhuphone: base_yezhuphone,
        monitorstime: base_monitorstime
    };

    loaddingshow();
    $.post("/Setting/SaveBridgeDetailBaseInfo", subdata,
        function (result) {
            if (result) {
                layer.msg("保存成功");
                $(".projectInfo").removeClass("active");
                $(".projectInfo").data("isload", false);
            }
            loaddinghide();
        }
    );
}

/*角色信息部分*/
function AddRoleInfo(obj) {
    $("#roleid").val("");
    $("#rolename").val("");
    $("#roleremark").val("");
    showDialog(500, "Model_AddRoleInfoWindow", $(obj).parents(".modal").css("z-index") * 1 + 1);
}
function EditRoleInfo(id, obj) {
    $("#roleid").val(id);
    $("#rolename").val($("#tr_" + id).data("name"));
    $("#roleremark").val($("#tr_" + id).data("remark"));
    showDialog(500, "Model_AddRoleInfoWindow", $(obj).parents(".modal").css("z-index") * 1 + 1);
}
function DeleteRoleInfo(id) {
    layer.confirm('删除角色信息 ? 删除后属本角色的用户的角色信息将被清空！\n确定要删除吗？', {
        btn: ['删除', '取消']
    }, function () {
        loaddingshow();
        $.post("/Role/DeleteRole", { id: id }, function (result) {
            if (result == "True") {
                loaddinghide();
                layer.msg("已成功删除！");
                LoadSystemSetting_RoleInfo_Data(1);
            } else {
                layer.alert("错误:" + result.Message, { title: "错误提示" });
            }
        });
    });
}
function SaveRoleInfo() {
    var id = $.trim($("#roleid").val());
    var name = $.trim($("#rolename").val());
    var remark = $.trim($("#roleremark").val());
    if (name == "") {
        layer.alert("角色名称不能为空！");
        return;
    }
    loaddingshow();
    if (id == "") {
        $.post("/Role/AddRole", { name: name, remark: remark }, function (result) {
            if (result == "True") {
                loaddinghide();
                layer.msg("已添加成功！");
                LoadSystemSetting_RoleInfo_Data(1);
                hideDialog("Model_AddRoleInfoWindow");
            } else {
                layer.alert("错误:" + result, { title: "错误提示" });
                loaddinghide();
            }
        });
    } else {
        $.post("/Role/UpdateRole", { id: id, name: name, remark: remark }, function (result) {
            if (result == "True") {
                loaddinghide();
                layer.msg("已修改成功！");
                LoadSystemSetting_RoleInfo_Data(1);
                hideDialog("Model_AddRoleInfoWindow");
            } else {
                layer.alert("错误:" + result, { title: "错误提示" });
                loaddinghide();
            }
        });
    }
}
function LoadSystemSetting_RoleInfo_Data(npage) {
    $("#roleinfotable tbody").html('<tr><td colspan="4" style="text-align: center;"><img src="/content/img/loading.gif"/></td></tr>');
    $.post("/Role/GetData", { npage: npage }, function (data) {
        var resultData = $.parseJSON(data);
        var htmls = "";
        var listdata = resultData.DataList;
        for (var i = 0; i < listdata.length; i++) {
            var remark = listdata[i].ROLE_INFO_REMARK;
            if (remark == null || remark == "NULL") {
                remark = "";
            }
            htmls += '<tr id="tr_' + listdata[i].ROLE_INFO_ID + '" data-name="' + listdata[i].ROLE_INFO_NAME + '" data-remark="' + remark + '">' +
                '<td>' + listdata[i].ROLE_INFO_NAME + '</td>' +
                '<td>' + remark + '</td>' +
                '<td>' + listdata[i].ROLE_INFO_CREATEDDATE.replace("T", " ") + '</td>' +
                '<td>' +
                '<a href="javascript:;" class="link" onclick="EditRoleInfo(\'' + listdata[i].ROLE_INFO_ID + '\',this)">编辑</a>' +
                '<a href="javascript:;" class="link" onclick="DeleteRoleInfo(\'' + listdata[i].ROLE_INFO_ID + '\')">删除</a>' +
                '</td>' +
                '</tr >';
        }
        $("#roleinfotable tbody").html(htmls);
        $("#roleinfotable").parent().parent().find("p .num").text(resultData.AllCount);
        InitSystemSettingPageLoadPager("rolelistpage", resultData.AllPage, npage, resultData.AllCount, "LoadSystemSetting_RoleInfo_Data");
    });
}
/*部门信息部分*/
function AddDepartmentInfo(obj) {
    $("#dept_id").val("");
    $("#dept_name").val("");
    $("#dept_principalman").val("");
    $("#dept_tel").val("");
    $("#dept_address").val("");
    $("#dept_fax").val("");
    $("#dept_capacity").val("");
    showDialog(500, "Model_AddDepartmentInfoWindow", $(obj).parents(".modal").css("z-index") * 1 + 1);
}
function EditDepartmentInfo(id, obj) {
    $("#dept_id").val(id);
    $("#dept_name").val($("#tr_" + id).data("name"));
    $("#dept_principalman").val($("#tr_" + id).data("principalman"));
    $("#dept_tel").val($("#tr_" + id).data("tel"));
    $("#dept_address").val($("#tr_" + id).data("address"));
    $("#dept_fax").val($("#tr_" + id).data("fax"));
    $("#dept_capacity").val($("#tr_" + id).data("capacity"));
    showDialog(500, "Model_AddDepartmentInfoWindow", $(obj).parents(".modal").css("z-index") * 1 + 1);
}
function DeleteDepartmentInfo(id) {
    layer.confirm('您确定要删除吗？', {
        btn: ['删除', '取消']
    }, function () {
        loaddingshow();
        $.post("/Department/DeleteDepartment", { id: id }, function (result) {
            if (result == "True") {
                loaddinghide();
                layer.msg("已成功删除！");
                LoadSystemSetting_DepartmentInfo_Data(1);
            } else {
                layer.alert("错误:" + result.Message, { title: "错误提示" });
            }
        });
    });
}
function SaveDepartmentInfo() {
    var id = $.trim($("#dept_id").val());
    var name = $.trim($("#dept_name").val());
    var principalman = $.trim($("#dept_principalman").val());
    var tel = $.trim($("#dept_tel").val());
    var address = $.trim($("#dept_address").val());
    var fax = $.trim($("#dept_fax").val());
    var capacity = $.trim($("#dept_capacity").val());
    if (capacity == "" || (capacity * 1) < 1) {
        layer.alert("部门人数不能为空，并且必须大于0！");
        return;
    }

    if (name == "") {
        layer.alert("部门名称不能为空！");
        return;
    } if (principalman == "") {
        layer.alert("负责人信息不能为空！");
        return;
    } if (tel == "") {
        layer.alert("部门电话不能为空！");
        return;
    }

    loaddingshow();
    if (id == "") {
        $.post("/Department/AddDepartment", { name: name, principalman: principalman, tel: tel, address: address, fax: fax, capacity: capacity }, function (result) {
            if (result == "True") {
                loaddinghide();
                layer.msg("已添加成功！");
                LoadSystemSetting_DepartmentInfo_Data(1);
                hideDialog("Model_AddDepartmentInfoWindow");
            } else {
                layer.alert("错误:" + result, { title: "错误提示" });
                loaddinghide();
            }
        });
    } else {
        $.post("/Department/UpdateDepartment", { id: id, name: name, principalman: principalman, tel: tel, address: address, fax: fax, capacity: capacity }, function (result) {
            if (result == "True") {
                loaddinghide();
                layer.msg("已修改成功！");
                LoadSystemSetting_DepartmentInfo_Data(1);
                hideDialog("Model_AddDepartmentInfoWindow");
            } else {
                layer.alert("错误:" + result, { title: "错误提示" });
                loaddinghide();
            }
        });
    }
}
function LoadSystemSetting_DepartmentInfo_Data(npage) {
    $("#departmentinfotable tbody").html('<tr><td colspan="8" style="text-align: center;"><img src="/content/img/loading.gif"/></td></tr>');
    $.post("/Department/GetData", { npage: npage }, function (data) {
        var resultData = $.parseJSON(data);
        var htmls = "";
        var listdata = resultData.DataList;
        for (var i = 0; i < listdata.length; i++) {
            var remark = listdata[i].ROLE_INFO_REMARK;
            if (remark == null || remark == "NULL") {
                remark = "";
            }
            var fzr = listdata[i].DEPT_INFO_PRINCIPALMAN;
            if (fzr == null || fzr == "null" || fzr == undefined || fzr == "undefined") {
                fzr = "";
            }
            var dz = listdata[i].DEPT_INFO_ADDRESS;
            if (dz == null || dz == "null" || dz == undefined || dz == "undefined") {
                dz = "";
            }
            var yx = listdata[i].DEPT_INFO_MAIL;
            if (yx == null || yx == "null" || yx == undefined || yx == "undefined") {
                yx = "";
            }
            var dh = listdata[i].DEPT_INFO_TEL;
            if (dh == null || dh == "null" || dh == undefined || dh == "undefined") {
                dh = "";
            }
            var cz = listdata[i].SystemName;
            if (cz == null || cz == "null" || cz == undefined || cz == "undefined") {
                cz = "";
            }
            htmls += '<tr id="tr_' + listdata[i].DEPT_INFO_ID + '" data-name="' + listdata[i].DEPT_INFO_NAME + '" data-principalman="' + fzr + '" data-tel="' + dh + '" data-address="' + dz + '" data-mall="' + yx + '" data-fax="' + cz + '" data-capacity="' + listdata[i].DEPT_INFO_CAPACITY + '">' +
                '<td width="20%" >' + listdata[i].DEPT_INFO_NAME + '</td>' +
                '<td width="10%">' + fzr + '</td>' +
                '<td width="5%">' + dh + '</td>' +
                '<td width="20%">' + dz + '</td>' +
                '<td width="15%">' + yx + '</td>' +
                '<td width="15%">' + cz + '</td>' +
                '<td width="5%">' + (listdata[i].DEPT_INFO_CAPACITY == null ? 0 : listdata[i].DEPT_INFO_CAPACITY)  + '</td>' +
                '<td width="10%"><a href="javascript:void(0)" onclick="EditDepartmentInfo(\'' + listdata[i].DEPT_INFO_ID + '\',this)">编辑</a>&nbsp;&nbsp;<a href="javascript:void(0)" onclick="ShowLoadDepartmentAuthorizesWindow(\'' + listdata[i].DEPT_INFO_NAME + '\',\'' + listdata[i].DEPT_INFO_ID + '\')">权限设置</a>&nbsp;&nbsp;<a href="javascript:void(0)" onclick="DeleteDepartmentInfo(\'' + listdata[i].DEPT_INFO_ID + '\')">删除</a></td>' +
                '</tr>';
        }
        $("#departmentinfotable tbody").html(htmls);
        $("#departmentinfotable").parent().parent().find("p .num").text(resultData.AllCount);
        InitSystemSettingPageLoadPager("departmentlistpage", resultData.AllPage, npage, resultData.AllCount, "LoadSystemSetting_DepartmentInfo_Data");
    });
}
function ShowLoadDepartmentAuthorizesWindow(name, depid) {
    $("#tablelisttitle").text("部门:" + name);
    $("#tablelisttitle").data("depid", depid);

    $.post("/Department/GetDepartmentAuthorizesTreeData", { departmentid: depid, bridgeid: $("#BridgeId").val() }, function (data) {
        showDialog(400, "Model_SetDepartmentAuthorizes_Window", 1051);
        BangDingAuthorizeTreeData(data);
    });
}
function BangDingAuthorizeTreeData(data) {
    var setting = {
        check: {
            enable: true,
            chkStyle: "checkbox"
        },
        data: {
            simpleData: {
                enable: true
            },
            keep: {
                parent: true
            }
        },
        callback: {
            onClick: this.onNodeClick
        },
        view: {
            selectedMulti: false
        }
    };
    $("#departmentauthorizestree").empty();
    if (data !== "[]") {
        $.fn.zTree.init($("#departmentauthorizestree"), setting, $.parseJSON(data));
    }
}
/*用户信息部分*/
function AddUserInfo(obj) {
    $("#user_id").val("");
    $("#user_name").val("");
    $("#user_nickname").val("");
    $("#user_pwd").val("");
    $("#user_pwd").parent("p").show();
    $("#user_tel").val("");
    $("#user_email").val("");
    showDialog(500, "Model_AddUserInfoWindow", $(obj).parents(".modal").css("z-index") * 1 + 1);
}
function EditUserInfo(id, obj) {
    $("#user_id").val(id);
    $("#user_deptid").val($("#tr_" + id).data("deptid"));
    $("#user_roleid").val($("#tr_" + id).data("roleid"));
    $("#user_name").val($("#tr_" + id).data("name"));
    $("#user_nickname").val($("#tr_" + id).data("nickname"));
    $("#user_tel").val($("#tr_" + id).data("tel"));
    $("#user_pwd").val("");
    $("#user_pwd").parent("p").hide();
    $("#user_email").val($("#tr_" + id).data("email"));
    showDialog(500, "Model_AddUserInfoWindow", $(obj).parents(".modal").css("z-index") * 1 + 1);
}
function DeleteUserInfo(id) {
    layer.confirm('您确定要删除吗？', {
        btn: ['删除', '取消']
    }, function () {
        loaddingshow();
        $.post("/User/DeleteUser", { id: id }, function (result) {
            if (result == "True") {
                loaddinghide();
                layer.msg("已成功删除！");
                LoadSystemSetting_UserInfo_Data(1);
            } else {
                layer.alert("错误:" + result.Message, { title: "错误提示" });
            }
        });
    });
}
function SaveUserInfo() {
    var id = $.trim($("#user_id").val());
    var deptid = $.trim($("#user_deptid").val());
    var roleid = $.trim($("#user_roleid").val());
    var name = $.trim($("#user_name").val());
    var nickname = $.trim($("#user_nickname").val());
    var pwd = $.trim($("#user_pwd").val());
    var tel = $.trim($("#user_tel").val());
    var email = $.trim($("#user_email").val());

    if (deptid == "") {
        layer.alert("部门不能为空！");
        return;
    }
    if (roleid == "") {
        layer.alert("角色不能为空！");
        return;
    }
    if (name == "") {
        layer.alert("登录名不能为空！");
        return;
    }
    if (nickname == "") {
        layer.alert("姓名不能为空！");
        return;
    }
    if (id == "" && pwd == "") {
        layer.alert("密码不能为空！");
        return;
    }
    if (tel == "" && tel == "") {
        layer.alert("手机号码不能为空！");
        return;
    }
    if (email == "" && email == "") {
        layer.alert("邮箱地址不能为空！");
        return;
    }
    loaddingshow();
    if (id == "") {
        $.post("/User/AddUser",
            { deptid: deptid, roleid: roleid, name: name, nickname: nickname, pwd: pwd, tel: tel, email: email },
            function (result) {
                if (result == "True") {
                    loaddinghide();
                    layer.msg("已添加成功！");
                    LoadSystemSetting_UserInfo_Data(1);
                    hideDialog("Model_AddUserInfoWindow");
                } else {
                    layer.alert("错误:" + result, { title: "错误提示" });
                    loaddinghide();
                }
            });
    } else {
        $.post("/User/UpdateUser",
            { id: id, deptid: deptid, roleid: roleid, name: name, nickname: nickname, tel: tel, email: email },
            function (result) {
                if (result == "True") {
                    loaddinghide();
                    layer.msg("已修改成功！");
                    LoadSystemSetting_UserInfo_Data(1);
                    hideDialog("Model_AddUserInfoWindow");
                } else {
                    layer.alert("错误:" + result, { title: "错误提示" });
                    loaddinghide();
                }
            });
    }
}
function LoadSystemSetting_UserInfo_Data(npage) {
    $.post("/User/GetNowUserDepartmentOrCreateDepartment", function (data) {
        var listdata = $.parseJSON(data);
        var htmls = "";
        for (var i = 0; i < listdata.length; i++) {
            htmls += '<option value="' + listdata[i].DEPT_INFO_ID + '">' + listdata[i].DEPT_INFO_NAME + '</option>';
        }
        $("#user_deptid").html(htmls);
    });
    $.post("/User/GetNowUserRolesOrCreateRoles", function (data) {
        var listdata = $.parseJSON(data);
        var htmls = "";
        for (var i = 0; i < listdata.length; i++) {
            htmls += '<option value="' + listdata[i].ROLE_INFO_ID + '">' + listdata[i].ROLE_INFO_NAME + '</option>';
        }
        $("#user_roleid").html(htmls);
    });

    $("#userinfotable tbody").html('<tr><td colspan="8" style="text-align: center;"><img src="/content/img/loading.gif"/></td></tr>');
    $.post("/User/GetData", { npage: npage }, function (data) {
        var resultData = $.parseJSON(data);
        var htmls = "";
        var listdata = resultData.DataList;
        for (var i = 0; i < listdata.length; i++) {
            htmls += '<tr class="cc" id="tr_' + listdata[i].USER_INFO_ID + '" data-name="' + listdata[i].USER_INFO_NAME + '" data-nickname="' + listdata[i].USER_INFO_NICKNAME + '"' +
                ' data-deptid="' + listdata[i].DEPT_INFO_ID + '" data-roleid="' + listdata[i].ROLE_INFO_ID + '" data-tel="' + listdata[i].USER_INFO_TEL + '" data-email="' + listdata[i].USER_INFO_EMAIL + '">' +
                '<td width="25%">' + listdata[i].USER_INFO_NICKNAME + '</td>' +
                '<td width="10%">' + listdata[i].USER_INFO_NAME + '</td>' +
                '<td width="20%">' + (listdata[i].ROLE_INFO_NAME == null ? '' : listdata[i].ROLE_INFO_NAME) + '</td>' +
                '<td width="25%">' + (listdata[i].DEPT_INFO_NAME == null ? '' : listdata[i].DEPT_INFO_NAME) + '</td>' +
                '<td width="10%">' + (listdata[i].USER_INFO_CREATEDDATE == null ? '' : listdata[i].USER_INFO_CREATEDDATE.split('T')[0]) + '</td>' +
                '<td width="10%">' +
                '<a href="javascript:void(0)" onclick="EditUserInfo(\'' + listdata[i].USER_INFO_ID + '\',this)">编辑</a>&nbsp;&nbsp;' +
                '<a href="javascript:void(0)" onclick="DeleteUserInfo(\'' + listdata[i].USER_INFO_ID + '\')">删除</a>' +
                '</td>' +
                '</tr>';
        }
        $("#userinfotable tbody").html(htmls);
        $("#userinfotable").parent().parent().find("p .num").text(resultData.AllCount);
        InitSystemSettingPageLoadPager("userlistpage", resultData.AllPage, npage, resultData.AllCount, "LoadSystemSetting_UserInfo_Data");
    });
}
/*权限信息部分*/
var roletruesetting;
function LoadSystemSetting_Authorizes_Data() {
    $.post("/Authorizes/GetNowUserRolesOrNowUserCreateRoles", function (data) {
        var listdata = $.parseJSON(data);
        var htmls = '<option value="">--请选择--</option>';
        for (var i = 0; i < listdata.length; i++) {
            htmls += '<option value="' + listdata[i].ROLE_INFO_ID + '">' + listdata[i].ROLE_INFO_NAME + '</option>';
        }
        $("#setroleselect").html(htmls);
    });
    roletruesetting = {
        check: {
            enable: true,
            chkStyle: "checkbox"
        },
        data: {
            simpleData: {
                enable: true
            },
            keep: {
                parent: true
            }
        },
        callback: {
            onClick: this.onNodeClick
        },
        view: {
            selectedMulti: false
        }
    }
    $("#AuthorizesTree").empty();
    $("#AuthorizesSaveBtn").attr("disabled", "disabled");
}
function LoadRoleAuthorizesData() {
    var roleid = $("#setroleselect").val();
    if (roleid == "") {
        layer.msg("请选择角色信息");
        $("#AuthorizesTree").empty();
        $("#AuthorizesSaveBtn").attr("disabled", "disabled");
        return;
    }
    loaddingshow();
    $("#AuthorizesTree").empty();
    $.post("/Authorizes/GetTreeData", { roleid: roleid, bridgeid: $("#BridgeId").val() }, function (data) {
        BangDingTreeData(data);
        loaddinghide();
    });
}
function BangDingTreeData(data) {
    $("#AuthorizesTree").empty();
    if (data != "[]") {
        $.fn.zTree.init($("#AuthorizesTree"), roletruesetting, $.parseJSON(data));
        $("#AuthorizesSaveBtn").removeAttr("disabled");
    }
}
function SaveAuthorizesInfo() {
    var roleid = $("#setroleselect").val();
    //功能权限
    var treeNodes = $.fn.zTree.getZTreeObj("AuthorizesTree").getCheckedNodes(true);
    var checkedNodeIds = "";
    for (var i = 0; i < treeNodes.length; i++) {
        checkedNodeIds += treeNodes[i].xid + ",";
    }
    $.post("/Authorizes/SaveAuthorizes", { roleid: roleid, nodeids: checkedNodeIds }, function (result) {
        if (result == "True") {
            loaddinghide();
            layer.msg("已保存成功！");
        } else {
            layer.alert("错误:" + result, { title: "错误提示" });
            loaddinghide();
        }
    });
}
/*实时数据设置*/
function SetNowShowRealDataSet(obj) {
    $(".systemsettingtab_21 p span").removeClass("active");
    $(".systemsettingtab_21 div table").hide();
    $(obj).addClass("active");
    LoadSystemSetting_RealDataSetting_Data();
}
function LoadSystemSetting_RealDataSetting_Data(showtype) {
    $("#realdatainfotable_" + showtype).show();
    $.post("/Setting/GetRealDataSetting", { type: showtype }, function (result) {
        var resultData = $.parseJSON(result);
        var htmls = "";
        console.log(resultData);
        for (var i = 0; i < resultData.length; i++) {
            htmls += '<tr>' +
                '<td>' + resultData[i].BridgeName + '</td >' +
                '<td>' + resultData[i].DataTypeName + '</td>' +
                '<td style="text-align: left"><input type="text" class="scoketaddress" data-bridgeid="' + resultData[i].BridgeId + '" data-type="' + resultData[i].DataType + '" value="' + resultData[i].SocketAdd + '"></td>' +
                '</tr>';
        }
        $("#realdatainfotable_" + showtype + " tbody").html(htmls);
        $("#SaveReadDataSetBtn").data("type", showtype);
    });
}

function SavePointRealDataSetting() {
    loaddingshow();
    var ntype = $("#SaveReadDataSetBtn").data("type");
    var datas = $(".scoketaddress");
    var datastr = new Array();
    for (var i = 0; i < datas.length; i++) {
        var value = $(datas[i]).val();
        if (ntype == $(datas[i]).data("type")) {
            datastr.push({
                bridgeid: $(datas[i]).data("bridgeid"),
                value: value,
                type: $(datas[i]).data("type")
            });
        }
    }
    $("#SaveReadDataSetBtn").attr("disabled", "disabled");
    $.post("/Setting/SavePointRealDataSetting", { type: $("#SaveReadDataSetBtn").data("type"), datasjson: JSON.stringify(datastr) }, function (result) {
        if (result == "True") {
            layer.msg("保存成功！");
        } else {
            layer.msg("保存失败！" + result);
        }

        $("#SaveReadDataSetBtn").removeAttr("disabled");
        loaddinghide();
    });
}

//系统设置通用分页
function InitSystemSettingPageLoadPager(showid, pages, curpage, allcount, fun) {
    laypage({
        cont: showid,
        pages: pages, //可以叫服务端把总页数放在某一个隐藏域，再获取
        curr: function () { //通过url获取当前页，也可以同上（pages）方式获取
            if (curpage.isNaN) {
                var page = location.search.match(/page=(\d+)/);
                return page ? page[1] : 1;
            }
            return curpage;
        }(),
        groups: 5, //连续显示分页数
        jump: function (e, first) { //触发分页后的回调
            if (!first) { //一定要加此判断，否则初始时会无限刷新
                var f = fun + "(" + e.curr + ")";
                eval(f);
            }
        },
        skip: true //是否开启跳页
    });
    loaddinghide();
}

function ShowSystemSetting_WarningData() {
    GetMsgTable();
    LoadBaseConfig();
}

function GetMsgTable() {
    var urlstr = $("#DataApiAddress").val() + 'api/msgconfig/GetAllMsgInfo';
    $("#msgInfoTbale").html("");
    $.ajax({
        url: urlstr,
        type: "POST",
        success: function (datas) {
            if (datas.Code === 200) {
                var data = datas.Result;
                if (data) {
                    var htmls = "";
                    for (var i = 0; i < data.length; i++) {
                        var name = data[i].Name;
                        var id = data[i].Id;
                        var type = "";
                        if (data[i].HasSms !== 0) {
                            type += "短信、";
                        }
                        if (data[i].HasEmail !== 0) {
                            type += "邮件、";
                        }
                        if (data[i].HasJpush !== 0) {
                            type += "Jpush、";
                        }
                        if (data[i].HasWeixin !== 0) {
                            type += "公众号、";
                        }
                        if (data[i].HasStationLetter !== 0) {
                            type += "站内信、";
                        }
                        var enable = "启用";
                        var ee = 1;
                        if (data[i].Enable === 1) {
                            enable = "停用";
                            ee = 0;
                        }

                        htmls += '<div class="messageItem">' +
                            '<div class="messageContent">' +
                            '<div class="messageFlex" > ' +
                            '<span class="flex-2" > ' + name + '</span > ' +
                            '<span class="flex-1" > ' + type + '</span > ' +
                            '<div class="flex-1 messageOpeation clearfix" > ' +
                            '<a href="javascript:void(0);" data-msgdata=' + JSON.stringify(data[i]) + ' onclick="editeMsg(this);">编辑</a>' +
                            '<a href = "javascript:void(0);" onclick="setMsgEnable(\'' + id + '\',\'' + enable + '\',' + ee + ');">' + enable + '</a > ' +
                            '<a href="javascript:void(0);" onclick="delMsgInfo(\'' + id + '\');">删除</a>' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                    }
                    $("#msgInfoTbale").html(htmls);
                }
            }
        },
        error: function (datas) {

        }
    });

}

function delMsgInfo(msgId) {
    var rs = confirm("确定删除？");
    if (rs) {
        $.get($("#DataApiAddress").val() + "api/msgconfig/SetMsgInfoDel/" + msgId, {}, function (result) {
            if (result.Code === 200) {
                GetMsgTable();
            } else {
                layer.alert(result.Message);
            }
        });
    }
}

function setMsgEnable(msgId, enable, ee) {
    var rs = confirm("确定" + enable + "？");
    if (rs) {
        $.get($("#DataApiAddress").val() + "api/msgconfig/SetMsgInfoEnable/" + msgId + "/" + ee, {}, function (result) {
            if (result.Code === 200) {
                GetMsgTable();
            } else {
                layer.alert(result.Message);
            }
        });
    }
}

function LoadBaseConfig() {
    var urlstr = $("#DataApiAddress").val() + 'api/msgconfig/GetBaseTypeInfoConfigs';
    $.ajax({
        url: urlstr,
        type: "POST",
        success: function (datas) {
            if (datas.Code == 200) {
                var data = datas.Result;
                if (data) {
                    var htmls = "";
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].Name === 'SMS') {
                            $("#sms_acount").val(data[i].AppId);
                            $("#sms_password").val(data[i].AppPwd);
                            $("#sms_url").val(data[i].AppUrl);
                            $("#sms_id").val(data[i].Id);
                            $("#sms_name").val(data[i].Name);
                        }
                        if (data[i].Name === 'Jpush') {
                            $("#jpush_acount").val(data[i].AppId);
                            $("#jpush_password").val(data[i].AppPwd);
                            $("#jpush_url").val(data[i].AppUrl);
                            $("#jpush_id").val(data[i].Id);
                            $("#jpush_name").val(data[i].Name);
                        }
                        if (data[i].Name === 'Email') {
                            $("#email_acount").val(data[i].AppId);
                            $("#email_password").val(data[i].AppPwd);
                            $("#email_url").val(data[i].AppUrl);
                            $("#email_id").val(data[i].Id);
                            $("#email_name").val(data[i].Name);
                        }
                        if (data[i].Name === 'WeiXin') {
                            $("#wx_acount").val(data[i].AppId);
                            $("#wx_password").val(data[i].AppPwd);
                            $("#wx_url").val(data[i].AppUrl);
                            $("#wx_id").val(data[i].Id);
                            $("#wx_name").val(data[i].Name);
                        }
                    }
                }
            }
        },
        error: function (datas) {

        }
    });
}

function saveBaseMsgConfig() {
    var jsons = "[";

    jsons += '{ ' +
        '"Id": "' + $("#sms_id").val() + '", ' +
        '"Name": "' + $("#sms_name").val() + '", ' +
        '"AppId": "' + $("#sms_acount").val() + '", ' +
        '"AppPwd": "' + $("#sms_password").val() + '", ' +
        '"AppUrl": "' + $("#sms_url").val() + '"' +
        '},';

    jsons += '{ ' +
        '"Id": "' + $("#jpush_id").val() + '", ' +
        '"Name": "' + $("#jpush_name").val() + '", ' +
        '"AppId": "' + $("#jpush_acount").val() + '", ' +
        '"AppPwd": "' + $("#jpush_password").val() + '", ' +
        '"AppUrl": "' + $("#jpush_url").val() + '"' +
        '},';

    jsons += '{ ' +
        '"Id": "' + $("#email_id").val() + '", ' +
        '"Name": "' + $("#email_name").val() + '", ' +
        '"AppId": "' + $("#email_acount").val() + '", ' +
        '"AppPwd": "' + $("#email_password").val() + '", ' +
        '"AppUrl": "' + $("#email_url").val() + '"' +
        '},';

    jsons += '{ ' +
        '"Id": "' + $("#email_id").val() + '", ' +
        '"Name": "' + $("#email_name").val() + '", ' +
        '"AppId": "' + $("#email_acount").val() + '", ' +
        '"AppPwd": "' + $("#email_password").val() + '", ' +
        '"AppUrl": "' + $("#email_url").val() + '"' +
        '}';

    jsons += ']';
    var urlstr = $("#DataApiAddress").val() + 'api/msgconfig/BaseTypeInfoConfig?jsonStr=' + jsons;

    $.ajax({
        url: urlstr,
        type: "POST",
        success: function (datas) {
            if (datas.Code === 200) {
                var data = datas.Result;
                if (data) {
                    layer.alert("修改保成功!");
                } else {
                    layer.alert("修改保存失败!");
                }
            }
        },
        error: function (datas) {

        }
    });
}

function clearMsgInfo() {
    $("#sl_add_sltemp").empty();
    $("#sl_add_jpushtemp").empty();
    $("#sl_add_smstemp").empty();
    $("#sl_add_emailtemp").empty();
    $("#sl_add_wxtemp").empty();
    $("#add_msg_name").val("");
    $("#ck_add_hassl").attr("checked", false);
    $("#ck_add_hasjpush").attr("checked", false);
    $("#ck_add_hassms").attr("checked", false);
    $("#ck_add_hasemail").attr("checked", false);
    $("#ck_add_haswx").attr("checked", false);
    $("#ck_add_soundlight").attr("checked", false);
}

function loadAddMsgInfo() {
    clearMsgInfo();
    var tempurlstr = $("#DataApiAddress").val() + 'api/msgconfig/GetMsgTempleteInfos';
    var smstemps = [];
    var emailtemps = [];
    var jpushtemps = [];
    var wxtemps = [];
    var sltemps = [];

    $.ajax({
        url: tempurlstr,
        type: "POST",
        success: function (datas) {
            if (datas.Code === 200) {
                var data = datas.Result;
                for (var i = 0; i < data.length; i++) {
                    if (data[i].Type === 1) {
                        sltemps.push(data[i]);
                    }
                    if (data[i].Type === 2) {
                        jpushtemps.push(data[i]);
                    }
                    if (data[i].Type === 3) {
                        smstemps.push(data[i]);
                    }
                    if (data[i].Type === 4) {
                        emailtemps.push(data[i]);
                    }
                    if (data[i].Type === 5) {
                        wxtemps.push(data[i]);
                    }
                }

                $("#sl_add_sltemp").append("<option value='0'>请选择模板</option>");//新增
                for (var o = 0; o < sltemps.length; o++) {
                    $("#sl_add_sltemp").append("<option value='" + sltemps[o].Code + "'>" + sltemps[o].Name + "</option>");//新增
                }

                $("#sl_add_jpushtemp").append("<option value='0'>请选择模板</option>");//新增
                for (var j = 0; j < jpushtemps.length; j++) {
                    $("#sl_add_jpushtemp").append("<option value='" + jpushtemps[j].Code + "'>" + jpushtemps[j].Name + "</option>");//新增
                }

                $("#sl_add_smstemp").append("<option value='0'>请选择模板</option>");//新增
                for (var k = 0; k < smstemps.length; k++) {
                    $("#sl_add_smstemp").append("<option value='" + smstemps[k].Code + "'>" + smstemps[k].Name + "</option>");//新增
                }

                $("#sl_add_emailtemp").append("<option value='0'>请选择模板</option>");//新增
                for (var m = 0; m < emailtemps.length; m++) {
                    $("#sl_add_emailtemp").append("<option value='" + emailtemps[m].Code + "'>" + emailtemps[m].Name + "</option>");//新增
                }

                $("#sl_add_wxtemp").append("<option value='0'>请选择模板</option>");//新增
                for (var n = 0; n < wxtemps.length; n++) {
                    $("#sl_add_wxtemp").append("<option value='" + wxtemps[n].Code + "'>" + wxtemps[n].Name + "</option>");//新增
                }
            }
        },
        error: function (datas) {

        }
    });
    var userDeptId = $("#current_userDeptid").val();
    var userurlstr = $("#DataApiAddress").val() + 'api/msgconfig/GetAllUser?deptid=' + userDeptId;
    $("#add_msg_users").empty();

    $.ajax({
        url: userurlstr,
        type: "POST",
        success: function (datas) {
            if (datas.Code === 200) {
                var data = datas.Result;
                var userhtml = "";
                for (var i = 0; i < data.length; i++) {
                    userhtml += '<li role="presentation" class="addPeopleitem">'
                        + '<input type = "checkbox" name = "" value = "' + data[i].USER_INFO_ID + '" >'
                        + '<span class="checkboxStyle"></span> '
                        + '<span class="peopleName">' + data[i].USER_INFO_NICKNAME + '(' + data[i].DeptName + ')' + '</span>'
                        + '</li >';
                }
                $("#add_msg_users").html(userhtml);
            }
        },
        error: function (datas) {

        }
    });


    $("#addMessageModal").modal("show");
}

function addMsgInfo() {
    var name = $("#add_msg_name").val();
    //var hassl = $("#ck_add_hassl").attr("checked");
    //var hasjpus = $("#ck_add_hasjpush").attr("checked");
    //var hassms = $("#ck_add_hassms").attr("checked");
    //var hasemail = $("#ck_add_hasemail").attr("checked");
    //var haswx = $("#ck_add_haswx").attr("checked");
    var sltemp = $("#sl_add_sltemp").val();
    var jpushtemp = $("#sl_add_jpushtemp").val();
    var smstemp = $("#sl_add_smstemp").val();
    var emailtemp = $("#sl_add_emailtemp").val();
    var wxtemp = $("#sl_add_wxtemp").val();
    var hassl = (sltemp == 0 ? 0 : 1);
    var hasjpus = (jpushtemp == 0 ? 0 : 1);
    var hassms = (smstemp == 0 ? 0 : 1);
    var hasemail = (emailtemp == 0 ? 0 : 1);
    var haswx = (wxtemp == 0 ? 0 : 1);
    var hassoundlight = $('#ck_add_hassoundlight').is(':checked') ? 1 : 0;

    var cklist = $('#add_msg_users input[type="checkbox"]');
    var userids = "";

    cklist.each(function () {
        if ($(this).is(':checked')) {
            userids += '"' + $(this).val() + '",';
        }
    });
    if (cklist && cklist.length > 0) {
        userids = userids.substring(0, userids.length - 1);
    }
    var jsons = '{'
        + '"Name": "' + name + '",'
        + '"HasSms": ' + hassms + ','
        + '"SmsTemplete": ' + smstemp + ','
        + '"HasEmail": ' + hasemail + ','
        + '"EmailTemplete": ' + emailtemp + ','
        + '"HasJpush": ' + hasjpus + ','
        + '"JpushTemplete": ' + jpushtemp + ','
        + '"HasWeixin": ' + haswx + ','
        + '"WeixinTemplete": ' + wxtemp + ','
        + '"HasStationLetter": ' + hassl + ','
        + '"StationLetterTemplete": ' + sltemp + ','
        + '"HasSoundLight": ' + hassoundlight + ','
        + '"UserIds": [' + userids + '],'
        + '"IsDel": 0,'
        + '"Enable": 1'
        + '}';
    var urlstr = $("#DataApiAddress").val() + 'api/msgconfig/AddMsgInfo?jsonStr=' + jsons;
    $.ajax({
        url: urlstr,
        type: "POST",
        success: function (datas) {
            if (datas.Code === 200) {
                var data = datas.Result;
                if (data) {
                    GetMsgTable();
                    layer.alert("添加保存成功!");
                } else {
                    layer.alert("添加保存失败!");
                }
            }
        },
        error: function (datas) {

        }
    });
}


function editeMsg(doc) {
    var obj = $(doc).data("msgdata");
    $("#sl_edit_sltemp").empty();
    $("#sl_edit_jpushtemp").empty();
    $("#sl_edit_smstemp").empty();
    $("#sl_edit_emailtemp").empty();
    $("#sl_edit_wxtemp").empty();
    var tempurlstr = $("#DataApiAddress").val() + 'api/msgconfig/GetMsgTempleteInfos';
    var smstemps = [];
    var emailtemps = [];
    var jpushtemps = [];
    var wxtemps = [];
    var sltemps = [];

    $.ajax({
        url: tempurlstr,
        type: "POST",
        success: function (datas) {
            if (datas.Code === 200) {
                var data = datas.Result;
                for (var i = 0; i < data.length; i++) {
                    if (data[i].Type === 1) {
                        sltemps.push(data[i]);
                    }
                    if (data[i].Type === 2) {
                        jpushtemps.push(data[i]);
                    }
                    if (data[i].Type === 3) {
                        smstemps.push(data[i]);
                    }
                    if (data[i].Type === 4) {
                        emailtemps.push(data[i]);
                    }
                    if (data[i].Type === 5) {
                        wxtemps.push(data[i]);
                    }
                }

                $("#sl_edit_sltemp").append("<option value='0'>请选择模板</option>");//新增
                for (var o = 0; o < sltemps.length; o++) {
                    $("#sl_edit_sltemp").append("<option value='" + sltemps[o].Code + "'>" + sltemps[o].Name + "</option>");//新增
                }

                $("#sl_edit_jpushtemp").append("<option value='0'>请选择模板</option>");//新增
                for (var j = 0; j < jpushtemps.length; j++) {
                    $("#sl_edit_jpushtemp").append("<option value='" + jpushtemps[j].Code + "'>" + jpushtemps[j].Name + "</option>");//新增
                }

                $("#sl_edit_smstemp").append("<option value='0'>请选择模板</option>");//新增
                for (var k = 0; k < smstemps.length; k++) {
                    $("#sl_edit_smstemp").append("<option value='" + smstemps[k].Code + "'>" + smstemps[k].Name + "</option>");//新增
                }

                $("#sl_edit_emailtemp").append("<option value='0'>请选择模板</option>");//新增
                for (var m = 0; m < emailtemps.length; m++) {
                    $("#sl_edit_emailtemp").append("<option value='" + emailtemps[m].Code + "'>" + emailtemps[m].Name + "</option>");//新增
                }

                $("#sl_edit_wxtemp").append("<option value='0'>请选择模板</option>");//新增
                for (var n = 0; n < wxtemps.length; n++) {
                    $("#sl_edit_wxtemp").append("<option value='" + wxtemps[n].Code + "'>" + wxtemps[n].Name + "</option>");//新增
                }

                $("#edit_msg_name").val(obj.Name);
                $("#edit_msg_id").val(obj.Id);
                $("#sl_edit_sltemp").val(obj.StationLetterTemplete);
                $("#sl_edit_jpushtemp").val(obj.JpushTemplete);
                $("#sl_edit_smstemp").val(obj.SmsTemplete);
                $("#sl_edit_emailtemp").val(obj.EmailTemplete);
                $("#sl_edit_wxtemp").val(obj.WeixinTemplete);
                $("#ck_edit_hassl").prop("checked", obj.HasStationLetter === 0 ? false : true);
                $("#ck_edit_hasjpush").prop("checked", obj.HasJpush === 0 ? false : true);
                $("#ck_edit_hassms").prop("checked", obj.HasSms === 0 ? false : true);
                $("#ck_edit_hasemail").prop("checked", obj.HasEmail === 0 ? false : true);
                $("#ck_edit_haswx").prop("checked", obj.HasWeixin === 0 ? false : true);

                if ($("#NowSystemType").data("hassoundlight").toString().toLowerCase() === "true") {
                    $("#addMessageModal .soundlightset").show();
                    $("#editMessageModal .soundlightset").show();
                    $("#ck_edit_soundlight").prop("checked", (obj.HasSoundLight === 0 ? false : true));
                }
                else {
                    $("#addMessageModal .soundlightset").hide();
                    $("#editMessageModal .soundlightset").hide();
                    $("#ck_edit_soundlight").prop("checked", false);
                }
                $("#SoundMinuteValue").val(obj.SoundMinuteValue);
            }
        },
        error: function (datas) {

        }
    });
    var userDeptId = $("#current_userDeptid").val();
    var userurlstr = $("#DataApiAddress").val() + 'api/msgconfig/GetAllReceiverById/' + obj.Id + "?deptid=" + userDeptId;
    $("#edit_msg_users").empty();

    $.ajax({
        url: userurlstr,
        type: "GET",
        success: function (datas) {

            if (datas.Code == 200) {
                var data = datas.Result;
                var userhtml = "";
                for (var i = 0; i < data.length; i++) {
                    var ck = '';
                    if (data[i].Selected) {
                        ck = 'checked = "checked"';
                    }
                    userhtml += '<li role="presentation" class="addPeopleitem">'
                        + '<input type="checkbox" ' + ck + ' name ="" value = "' + data[i].USER_INFO_ID + '" >'
                        + '<span class="checkboxStyle"></span> '
                        + '<span class="peopleName">' + data[i].USER_INFO_NICKNAME + '(' + data[i].DeptName + ')' + '</span>'
                        + '</li >';
                }
                $("#edit_msg_users").html(userhtml);
            }
        },
        error: function (datas) {

        }
    });

    $("#editMessageModal").modal("show");
}

function editMsgInfo() {
    debugger
    var name = $("#edit_msg_name").val();
    var id = $("#edit_msg_id").val();
    //var hassl = $("#ck_add_hassl").attr("checked");
    //var hasjpus = $("#ck_add_hasjpush").attr("checked");
    //var hassms = $("#ck_add_hassms").attr("checked");
    //var hasemail = $("#ck_add_hasemail").attr("checked");
    //var haswx = $("#ck_add_haswx").attr("checked");
    var sltemp = $("#sl_edit_sltemp").val();
    var jpushtemp = $("#sl_edit_jpushtemp").val();
    var smstemp = $("#sl_edit_smstemp").val();
    var emailtemp = $("#sl_edit_emailtemp").val();
    var wxtemp = $("#sl_edit_wxtemp").val();
    var hassl = (sltemp == 0 ? 0 : 1);
    var hasjpus = (jpushtemp == 0 ? 0 : 1);
    var hassms = (smstemp == 0 ? 0 : 1);
    var hasemail = (emailtemp == 0 ? 0 : 1);
    var haswx = (wxtemp == 0 ? 0 : 1);
    var hassoundlight = $("#ck_edit_soundlight").is(':checked') ? 1 : 0;
    var soundMinuteValue = $.trim($("#SoundMinuteValue").val());

    var cklist = $('#edit_msg_users input[type="checkbox"]');
    var userids = "";

    cklist.each(function () {
        if ($(this).is(':checked')) {
            userids += '"' + $(this).val() + '",';
        }
    });
    if (cklist && cklist.length > 0) {
        userids = userids.substring(0, userids.length - 1);
    }

    var jsons = '{'
        + '"Id": "' + id + '",'
        + '"Name": "' + name + '",'
        + '"HasSms": ' + hassms + ','
        + '"SmsTemplete": ' + smstemp + ','
        + '"HasEmail": ' + hasemail + ','
        + '"EmailTemplete": ' + emailtemp + ','
        + '"HasJpush": ' + hasjpus + ','
        + '"JpushTemplete": ' + jpushtemp + ','
        + '"HasSoundLight": ' + hassoundlight + ','
        + '"SoundMinuteValue": ' + soundMinuteValue + ','
        + '"HasWeixin": ' + haswx + ','
        + '"WeixinTemplete": ' + wxtemp + ','
        + '"HasStationLetter": ' + hassl + ','
        + '"StationLetterTemplete": ' + sltemp + ','
        + '"UserIds": [' + userids + '],'
        + '"IsDel": 0,'
        + '"Enable": 1'
        + '}';
    var urlstr = $("#DataApiAddress").val() + 'api/msgconfig/UpdateMsgInfo?jsonStr=' + jsons;
    $.ajax({
        url: urlstr,
        type: "POST",
        success: function (datas) {
            if (datas.Code === 200) {
                var data = datas.Result;
                if (data) {
                    layer.alert("编辑保存成功!");
                    $("#editMessageModal").modal("hide");
                    GetMsgTable();
                } else {
                    layer.alert("编辑保存失败!");
                }
            }
        },
        error: function (datas) {

        }
    });
}

function msgcheckIni(obj, id) {
    var el = document.getElementById(id);
    if (!obj.checked) {
        el.options[0].selected = true;
    };
}

function changeatimetypeactiveclass(obj) {
    var p = $(obj).parent().find("a").removeClass("active");
    $(obj).addClass("active");
}

var serachtimer;
function changeInputText() {
    if (serachtimer) {
        clearTimeout(serachtimer);
    }
    serachtimer = setTimeout(function () {
        var q = $("#bridges_searcher_input").val();
        $("#bridges_searcher_ul").empty();
        $("#bridges_searcher_ul").html('<li><a class="nobr" href="javacript:void(0);">搜索中....</a></li>');
        loadBridgesBySearch(q);
    }, 500);
}

function loadBridgesBySearch(q) {
    $.ajax({
        url: "/home/GetBridgesBySerch?q=" + q,
        //data: { "jsonStr": jsons },
        type: "GET",
        //dataType: "json",
        //contentType: "application/json; charset=utf-8",
        success: function (datas) {
            $("#bridges_searcher_ul").empty();
            if (datas) {
                var data = jQuery.parseJSON(datas);
                var userhtml = "";
                if (data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        userhtml += '<li><a class="nobr" href="javascript:void(0);" onclick="GoBridge(\'' + data[i].Id + '\')">' + data[i].Name + '</a></li>';
                    }
                    $("#bridges_searcher_ul").html(userhtml);
                } else {
                    $("#bridges_searcher_ul").html('<li><a class="nobr" href="javacript: void (0);">无数据</a></li>');
                }

            }
        },
        error: function (datas) {
            $("#bridges_searcher_ul").html('<li><a class="nobr" href="javacript: void (0);">无数据</a></li>');
        }
    });
}

function ShowTimeLineWindow() {

}

function ShowWindowData_PointDataOverview() {
    var shows = $.parseJSON($("#PointDataStasticsDatas").val());
    $("#PointDataStasticsContent").html("<label id='pointdatastasticsloading' style='text-align:center;width: 100%;'><img src='/content/img/loading.gif'/></label>");
    for (var i = 0; i < shows.length; i++) {
        if (shows[i].IsShow) {
            var pointhtmls = "", pointcount = 0;
            var points = $("#panel" + shows[i].PointTypeId + ">ul>li");
            for (var p = 0; p < points.length; p++) {
                var id = $(points[p]).find(".menu_sec_name").data("pointid");
                var name = $(points[p]).find(".showtext").text();
                pointhtmls += '<option value="' + id + '">' + name + '</option>';
                pointcount++;
            }

            if (shows[i].PointTypeId === 14 || shows[i].PointTypeId === 11) {
                var pointhtmls = "";
                var points = $("#panel" + shows[i].PointTypeId + ">ul>li");
                for (var p = points.length; p > 0; p--) {
                    var id = $(points[p - 1]).find(".menu_sec_name").data("pointid");
                    var name = $(points[p - 1]).find(".showtext").text();
                    pointhtmls += '<option value="' + id + '">' + name + '</option>';
                }
                htmls = '<div class="rightBar-biaomian">' +
                    '<h3 class="rightBar-title">表面位移分析</h3>' +
                    '<input type="hidden" id="pointdatastastics_parameter_' + shows[i].PointTypeId + '" data-dataareavalue="' + shows[i].DataAreaValue + '" data-refreshvalue="' + shows[i].RefreshValue + '"/>' +
                    '<section class="rightBar-biaomian-fliter">' +
                    '<label class="rightBar-biaomian-label"><input type="radio" value="0" name="pointdatastastics_gnss_type" checked="checked" class="rightBar-biaomian-input" onchange="LoadPointDataStastics_GNSS(' + shows[i].PointTypeId + ');"><span>位移</span></label>' +
                    '<label class="rightBar-biaomian-label"><input type="radio" value="1" name="pointdatastastics_gnss_type" class="rightBar-biaomian-input"onchange="LoadPointDataStastics_GNSS(' + shows[i].PointTypeId + ');"><span>速率</span></label>' +
                    '<label class="rightBar-biaomian-label"><input type="radio" value="2" name="pointdatastastics_gnss_type" class="rightBar-biaomian-input"onchange="LoadPointDataStastics_GNSS(' + shows[i].PointTypeId + ');"><span>加速度</span></label>' +
                    '<select id="pointdatastastics_pointtype_' + shows[i].PointTypeId + '" ' + (pointcount > 1 ? "" : "disabled class='pointselectdisabled'") + ' onchange="LoadPointDataStastics_GNSS(' + shows[i].PointTypeId + ');">' + pointhtmls + '</select>' +
                    '<a class="pull-right biaomian-refresh" href="javascript:javascript:void(0);" onclick="LoadPointDataStastics_GNSS(' + shows[i].PointTypeId + ');"><i class="ico ico-refresh"></i></a>' +
                    '</section>' +
                    '</div>' +
                    '<div class="biaomian-top">' +
                    '<div class="chart-gaocheng" id="pointdatastastics_chart_' + shows[i].PointTypeId + '_gaocheng"></div>' +
                    '<section class="biaomian-stats-wrapper" id="pointdatastastics_gnss_gaocheng_result"></section>' +
                    '<div class="border-line"></div>' +
                    '</div>' +
                    '<div class="biaomian-bottom">' +
                    '<div class="chart-shuiping" id="pointdatastastics_chart_' + shows[i].PointTypeId + '_shuiping"></div>' +
                    '<section class="biaomian-stats-wrapper" id="pointdatastastics_gnss_shuiping_result"></section>' +
                    '</div>';
                $("#PointDataStasticsContent").append(htmls);
                LoadPointDataStastics_GNSS(shows[i].PointTypeId);
            }
            else {
                htmls = '<div class="rightBar-biaomian">' +
                    '<h3 class="rightBar-title">' + shows[i].PointTypeName + '数据分析</h3>' +
                    '<input type="hidden" id="pointdatastastics_parameter_' + shows[i].PointTypeId + '" data-dataareavalue="' + shows[i].DataAreaValue + '" data-refreshvalue="' + shows[i].RefreshValue + '"/>' +
                    '<section class="rightBar-biaomian-fliter">' +
                    '<select id="pointdatastastics_pointtype_' + shows[i].PointTypeId + '" ' + (pointcount > 1 ? "" : "disabled class='pointselectdisabled'") + ' onchange="LoadPointDataStastics_Other(' + shows[i].PointTypeId + ',\'' + shows[i].PointTypeName + '\');">' + pointhtmls + '</select>' +
                    '<a class="pull-right biaomian-refresh" href="javascript:javascript:void(0);" onclick="LoadPointDataStastics_Other(' + shows[i].PointTypeId + ',\'' + shows[i].PointTypeName + '\');"><i class="ico ico-refresh"></i></a>' +
                    '</section>' +
                    '</div>' +
                    '<div class="biaomian-top">' +
                    '<div class="chart-gaocheng" id="pointdatastastics_chart_' + shows[i].PointTypeId + '"></div>' +
                    '</div>';
                $("#PointDataStasticsContent").append(htmls);
                LoadPointDataStastics_Other(shows[i].PointTypeId, shows[i].PointTypeName);
            }
        }
    }
    $("#pointdatastasticsloading").remove();
}

function ShowWindowData_PointMapPositionOverview() {
    var $sectionSlider = $('.sectionSlider');
  
    
    if ($("#WindowPointSectionMapPositionEntitys").val() == "" || $("#WindowPointSectionMapPositionEntitys").val() == undefined) {
        $sectionSlider.html('<section class="noPointImg">暂无断面布点图，请增加断面布点图！</section >');
        return;
    };
    var pointEls = $("#monitorPoint .addpointtypepanel");
    $(".budian-sensor-list").html('');
    for (var i = 0; i < pointEls.length; i++) {
        var pointElid = pointEls.eq(i).data('id');
        var pointElname = pointEls.eq(i).data('name');
        $(".budian-sensor-list").append('<span><i class="icon ico-data-' + pointElid + '"></i>' + pointElname + '</span>')
    };
    var $datas = $.parseJSON($("#WindowPointSectionMapPositionEntitys").val());
    var $pointMapSlider = new Array();
    $pointMapSlider.push('<div class="carousel slide section-slider" id="section-slider">');
    $pointMapSlider.push('<section class="warning-top clearfix">');
    $pointMapSlider.push('<div class="warning-indicators pull-left">');
    $pointMapSlider.push('<a class="icon icon-left" href="#section-slider" role="button" data-slide="prev"></a><a class="icon icon-right" href="#section-slider" role="button" data-slide="next"></a>');
    $pointMapSlider.push('</div><h5>' + $datas[0].name + '</h5></section >');
    $pointMapSlider.push('<div class="carousel-inner" role="listbox">');
    for (var i = 0; i < $datas.length; i++) {
        if (i == 0) {
            $pointMapSlider.push('<section class="item active" data-name="' + $datas[i].name + '"><div class= "sectionImg" style="background-image:url(' + $datas[i].img + ')">');
        } else {
            $pointMapSlider.push('<section class="item" data-name="' + $datas[i].name + '"><div class="sectionImg" style="background-image:url(' + $datas[i].img + ')">');
        };
        var $sensorPosition = $datas[i].sensorMsg;
        for (var j = 0; j < $sensorPosition.length; j++) {
            $pointMapSlider.push('<span class="sensorPostion ico-data-' + $sensorPosition[j].name + '" style="left:' + $sensorPosition[j].left + ';top:' + $sensorPosition[j].top + '"></span>');
        };
        $pointMapSlider.push('</div></section >');
    };
    $pointMapSlider.push('</div></div>');

    $('.sectionSlider').html($pointMapSlider.join(''));
    $('.section-slider').carousel({
        interval: 0
    }).on('slide.bs.carousel',
        function (event) {
            setTimeout(function () {
                var $name = $(".section-slider .item.active").data("name");
                $('.section-slider h5').text($name);
            }, 800);
        });
    $('#sectionModal').on('shown.bs.modal',
        function (e) {
            var $pointItems = new Array();
            for (var i = 0; i < $datas.length; i++) {
                var url = $datas[i].img;
                var filename = url.substring(url.lastIndexOf("/") + 1, url.length);
                filename = filename.substring(0, 3) + '...' + filename.substring(filename.length - 6, filename.length);
                $pointItems.push('<div class="ponitMapitem">');
                $pointItems.push('<div class="ponitMapitem-top">');
                $pointItems.push('<section class="pull-right ponitFunc">');
                $pointItems.push('<a href="javascript:;" class="uploadImg">上传图片<div id="uploadImgBtn' + $datas[i].id + '" class="uploadImgBtn" data-id="' + $datas[i].id + '"></div></a><a href="javascript:;" class="pointSet">布点配置</a><a href="javascript:;" class="pointMapDel"></a>');
                $pointItems.push('</section><section class="ponitImgCon"><input type="text" name="imgName" placeholder="布点图名称" value="' + $datas[i].name + '"/>');
                $pointItems.push('</section></div>');
                $pointItems.push('<div class="ponitMapitem-bottom clearfix"><span class= "pull-right">图片尺寸建议 宽480px, 高240px</span><span class="pull-left pointImgName">' + filename + '</span>');
                $pointItems.push('<a href="javascript:;" class="viewPointImg pull-left">预览<div class="pointImgCon"><img src="' + $datas[i].img + '" class="pointImg"></div></a></div >');
                $pointItems.push('<div class="pointSetBar"><section class= "pointSetBar-top" ><i class="pull-right ico ico-cancel-gray closePointSetBar"></i><p>用鼠标在图片上右击布点的位置，然后选择传感器</p></section >');
                $pointItems.push('<div class="sectionImg pointSetWrapper" oncontextmenu="javascript:return false;" data-image="' + $datas[i].img + '" style="background-image:url(' + $datas[i].img + ')">');
                var $sensorPosition = $datas[i].sensorMsg;
                for (var j = 0; j < $sensorPosition.length; j++) {
                    var $data_position = {
                        left: $sensorPosition[j].left,
                        top: $sensorPosition[j].top,
                        name: $sensorPosition[j].name,
                        id: $sensorPosition[j].id
                    };
                    $pointItems.push('<span  data-position=' + JSON.stringify($data_position) + ' class="sensorPostion ico-data-' + $sensorPosition[j].name + '" style="left:' + $sensorPosition[j].left + ';top:' + $sensorPosition[j].top + '"><section class="sensorPositionTool"><a href="javascript:;" class="editSensor">编辑</a><a href="javascript:;" class="delSensor">删除</a></section></span>');
                };
                $pointItems.push('<section class= "sectionLegend pointSelectList scroll">');
                for (var j = 0; j < pointEls.length; j++) {
                    var pointElid = pointEls.eq(j).data('id');
                    var pointElname = pointEls.eq(j).data('name');
                    $pointItems.push('<span><i class="icon ico-data-' + pointElid + '" data-name="' + pointElid + '"></i>' + pointElname + '</span>');
                };
                //$pointItems.push('<span><i class="icon icon-gaocheng" data-name="gaocheng"></i>高程位移</span><span><i class="icon icon-shuiping" data-name="shuiping"></i>水平位移</span><span><i class="icon icon-shenbu" data-name="shenbu"></i>深部位移</span>');
                $pointItems.push('</section></div >');
                $pointItems.push('</div></div >');
            };
            $('.ponitMapList').html($pointItems.join(''));
            var $uploadImgBtn = $('.uploadImgBtn');
            for (var i = 0; i < $uploadImgBtn.length; i++) {
                var newuploadno = $uploadImgBtn.eq(i).data('id');

                $('#uploadImgBtn' + newuploadno).uploadify({
                    'buttonText': "",
                    'swf': '/content/uploadify/uploadify.swf', //设置上传组件uploadify.swf的路径
                    'uploader': '/FileUpload/Upload/', //设置上传的Url接口
                    'cancelImg': '/content/uploadify/cancel.png',
                    'removeCompleted': true,
                    'hideButton': true,
                    'auto': true,
                    //'nowuploadno': newuploadno,
                    'multi': true,
                    'wmode': 'transparent',
                    'uploadLimit': 99,
                    'simUploadLimit': 99,
                    'fileTypeDesc': '* Files (.*)',
                    'onUploadStart': function (file) {
                        $("#uploadImgBtn" + newuploadno).uploadify("settings",
                            "formData",
                            { type: "", bridgeid: $('#BridgeId').val(), modelType: "" });
                    },
                    'onQueueComplete': function (queueData) { },
                    'onCancel': function (file) { },
                    'onUploadSuccess': function (file, resultdata, responese) {
                        var filedata = $.parseJSON(resultdata);
                        if (resultdata != '[]' && filedata != null) {
                            var url = "/" + filedata.path;
                            var filename = url.substring(url.lastIndexOf("/") + 1, url.length);
                            filename = filename.substring(0, 3) +
                                '...' +
                                filename.substring(filename.length - 6, filename.length);
                            var $this_parents = $('#uploadImgBtn' + newuploadno).parents('.ponitMapitem');
                            $this_parents.find('.ponitMapitem-bottom').find('.viewPointImg')
                                .html('预览<div class="pointImgCon"><img src="' + url + '" class="pointImg"></div>');
                            var $pointSetBar = new Array();
                            $pointSetBar.push('<section class="pointSetBar-top">');
                            $pointSetBar.push(
                                '<i class="pull-right ico ico-cancel-gray closePointSetBar"></i><p>用鼠标在图片上右击布点的位置，然后选择传感器</p>');
                            $pointSetBar.push('</section>');
                            $pointSetBar.push(
                                '<div class="sectionImg pointSetWrapper" oncontextmenu="javascript:return false;" data-image="' +
                                url +
                                '" style="background-image:url(' +
                                url +
                                ')">');
                            $pointSetBar.push('<section class="sectionLegend pointSelectList scroll">')
                            for (var j = 0; j < pointEls.length; j++) {
                                var pointElid = pointEls.eq(j).data('id');
                                var pointElname = pointEls.eq(j).data('name');
                                $pointSetBar.push('<span><i class="icon ico-data-' + pointElid + '" data-name="' + pointElid + '"></i>' + pointElname + '</span>');
                            };
                            $pointSetBar.push('</section>');
                            $pointSetBar.push('</div>');

                            $this_parents.find('.pointSetBar').html($pointSetBar.join(''));
                            $this_parents.find('.sectionImg').find('.sensorPostion ').remove();
                            $this_parents.find('.pointImgName').text(filename);
                        }
                    }
                });
            }
        });
}

function LoadPointDataStastics_GNSS(pointtypeid) {
    $("#pointdatastastics_chart_" + pointtypeid).html("<label style='width:100%;text-align:center'><img src='/content/img/loading.gif'/></label>");
    var pointid = $("#pointdatastastics_pointtype_" + pointtypeid).val();
    if (pointid == null || pointid == "") {
        $("#pointdatastastics_chart_" + pointtypeid + "_gaocheng").html("<label style='width:100%;text-align:center'>未筛选到任何传感器!</label>");
        $("#pointdatastastics_chart_" + pointtypeid + "_shuiping").html("<label style='width:100%;text-align:center'>未筛选到任何传感器!</label>");
        return;
    }
    var dataareavalue = $("#pointdatastastics_parameter_" + pointtypeid).data("dataareavalue");
    var refreshvalue = $("#pointdatastastics_parameter_" + pointtypeid).data("refreshvalue");
    var type = $("input[name='pointdatastastics_gnss_type']:checked").val();
    $.get($("#DataApiAddress").val() + "api/analysis/staticgnssdata/" + $("#BridgeId").val() + "/pointtype/" + pointtypeid + "/pointid/" + pointid + "/timespan/" + dataareavalue + "/chartdatatype/" + type,
        function (resultdata) {
            if (resultdata.Code === 200) {
                if (resultdata.Result.ResultDataJsons != "") {
                    var data = $.parseJSON(resultdata.Result.ResultDataJsons)[type];
                    var topdata = [];
                    var bottomdata = [];
                    for (var d = 0; d < data.length; d++) {
                        if (data[d].name.indexOf("_2D") > 0) {
                            topdata = data[d].data;
                        } else if (data[d].name.indexOf("_H") > 0) {
                            bottomdata = data[d].data;
                        }
                    }

                    var unit = "";
                    if ($("input[name='pointdatastastics_gnss_type']:checked").val() == "0") {//"时间-位移"
                        unit = "mm";
                    } else if ($("input[name='pointdatastastics_gnss_type']:checked").val() == "1") {//1"时间-速率"
                        unit = "mm/s";
                    } else {
                        unit = "mm/s²";
                    }
                    //绑定chart
                    $('#pointdatastastics_chart_' + pointtypeid + '_shuiping').highcharts({
                        chart: { zoomType: 'x', backgroundColor: '#485B69' },
                        title: { text: null },
                        subtitle: { text: '水平位移(' + unit + ')', style: { color: '#ffffff', x: 0 } },
                        exporting: { enabled: false },
                        xAxis: { lineWidth: 0.5, lineColor: "#FFFFFF", tickWidth: 0.5, labels: { style: { color: '#FFFFFF', fontSize: '12px' } }, type: 'datetime', dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%m-%d', week: '%m-%d', month: '%Y-%m', year: '%Y' } },
                        tooltip: { formatter: function () { return '<span style="font-size: 10px;">' + formatDateTime(new Date(this.x)) + '</span><br/>水平位移:<b>' + this.y + "</b> " + unit; } },
                        yAxis: { gridLineWidth: 0, lineWidth: 0.5, lineColor: "#FFFFFF", tickWidth: 0.5, labels: { style: { color: '#FFFFFF', fontSize: '12px' } }, title: { text: '' } },
                        plotOptions: { area: { fillColor: '#376EA7', lineWidth: 2, lineColor: '#2D7BCE' } },
                        legend: { enabled: false },
                        series: [{ type: 'area', name: '水平位移(' + unit + ')', data: topdata }],
                        credits: { enabled: false }
                    });
                    $('#pointdatastastics_chart_' + pointtypeid + '_gaocheng').highcharts({
                        chart: { zoomType: 'x', backgroundColor: '#485B69' },
                        title: { text: null },
                        subtitle: { text: '垂直位移(' + unit + ')', style: { color: '#ffffff', x: 0 } },
                        exporting: { enabled: false },
                        xAxis: { lineWidth: 0.5, lineColor: "#FFFFFF", tickWidth: 0.5, labels: { style: { color: '#FFFFFF', fontSize: '12px' } }, type: 'datetime', dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%m-%d', week: '%m-%d', month: '%Y-%m', year: '%Y' } },
                        plotOptions: { area: { fillColor: '#376EA7', lineWidth: 2, lineColor: '#2D7BCE' } },
                        tooltip: { formatter: function () { return '<span style="font-size: 10px;">' + formatDateTime(new Date(this.x)) + '</span><br/>垂直位移:<b>' + this.y + "</b> " + unit; } },
                        yAxis: { gridLineWidth: 0, lineWidth: 0.5, lineColor: "#FFFFFF", tickWidth: 0.5, labels: { style: { color: '#FFFFFF', fontSize: '12px' } }, title: { text: '' } },
                        legend: { enabled: false },
                        series: [{ type: 'area', name: '垂直位移(' + unit + ')', data: bottomdata }],
                        credits: { enabled: false }
                    });
                    //绑定结论
                    var result = $.parseJSON(resultdata.Result.ResultJsons);
                    $("#pointdatastastics_gnss_shuiping_result").html("<span class='biaomian-stats state" + result.D2State + "'>" + result.D2StateString + "</span>");
                    $("#pointdatastastics_gnss_gaocheng_result").html("<span class='biaomian-stats state" + result.HState + "'>" + result.HStateString + "</span>");
                }
                else {
                    console.log(resultdata.Result);
                    $("#pointdatastastics_chart_" + pointtypeid + "_shuiping").html("<label style='width:100%;text-align:center'>当前无数据!</label>");
                    $("#pointdatastastics_chart_" + pointtypeid + "_gaocheng").html("<label style='width:100%;text-align:center'>当前无数据!</label>");
                    $("#pointdatastastics_gnss_shuiping_result").html("<span class='biaomian-stats'>...</span>");
                    $("#pointdatastastics_gnss_gaocheng_result").html("<span class='biaomian-stats'>...</span>");
                }
            } else {
                $("#pointdatastastics_chart_" + pointtypeid + "_gaocheng").html("<label style='width:100%;text-align:center'>api数据加载失败!</label>");
                $("#pointdatastastics_chart_" + pointtypeid + "_shuiping").html("<label style='width:100%;text-align:center'>api数据加载失败!</label>");
                $("#pointdatastastics_gnss_shuiping_result").html("<span class='biaomian-stats'>...</span>");
                $("#pointdatastastics_gnss_gaocheng_result").html("<span class='biaomian-stats'>...</span>");
            }
        }
    );
}

function EditShow3DModel() {
    $("#ModelShowType").data("showedtype", "three3d");
    $("#model3d").html("");
    $.post("/Model/Index/" + $("#BridgeId").val() + "?isedit=true", {}, function (result) {
        try {
            $("#model3d").html(result);
            if (result != "") {
                $("#model3d").show();
                init3d();
                loaddinghide();
            }
        } catch (e) {
            console.log("加载模型页面异常:");
            console.log(e);
        } finally {
            loaddinghide();
        }
    });
}
function EditShowMapModel() {
    $("#ModelShowType").data("showedtype", "mapmodel");
    $("#model3d").html("");
    $.post("/Model/ModelMap/" + $("#BridgeId").val() + "?isedit=true", {}, function (result) {
        try {
            $("#model3d").html(result);
            if (result != "") {
                $("#model3d").show();
                init3dmodelmap();
                loaddinghide();
            }
        } catch (e) {
            console.log("加载地图页面异常:");
            console.log(e);
        } finally {
            loaddinghide();
        }
    });
}

function formatDateTime(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return h + ':' + minute;
};

function LoadPointDataStastics_Other(pointtypeid, pointtypename) {
    $("#pointdatastastics_chart_" + pointtypeid).html("<label style='width:100%;text-align:center'><img src='/content/img/loading.gif'/></label>");
    var pointid = $("#pointdatastastics_pointtype_" + pointtypeid).val();
    if (pointid == null || pointid == "") {
        $("#pointdatastastics_chart_" + pointtypeid).html("<label style='width:100%;text-align:center'>未筛选到任何传感器!</label>");
        return;
    }
    var dataareavalue = $("#pointdatastastics_parameter_" + pointtypeid).data("dataareavalue");
    var refreshvalue = $("#pointdatastastics_parameter_" + pointtypeid).data("refreshvalue");
    var getrealdataapitype = "";
    if (pointtypename === "水位") {
        getrealdataapitype = "swandata";
    } else if (pointtypename === "降雨量") {
        getrealdataapitype = "jylandata";
    } else if (pointtypename === "渗流") {
        getrealdataapitype = "slandata";
    } else if (pointtypename === "土压力") {
        getrealdataapitype = "tyliandata";
    } else if (pointtypename === "温度") {
        getrealdataapitype = "wdandata";
    } else if (pointtypename === "湿度") {
        getrealdataapitype = "sdandata";
    } else if (pointtypename === "偏移位移") {
        getrealdataapitype = "pywyandata";
    } else if (pointtypename === "图像位移") {
        getrealdataapitype = "txwyandata";
    } else if (pointtypename === "风速风向") {
        getrealdataapitype = "windandata";
    }

    window.clearInterval(p);
    var p = window.setInterval(BadingPointDataStastics_Other(pointtypeid, pointtypename, pointid, getrealdataapitype, dataareavalue), refreshvalue * 1000);
}

function BadingPointDataStastics_Other(pointtypeid, pointtypename, pointid, getrealdataapitype, dataareavalue) {
    if (getrealdataapitype === null || getrealdataapitype === "") {
        return;
    }
    var ntime = new Date();
    var endtime = ntime.format("yyyy-MM-dd");
    var starttime = ntime.addDays(ntime, -dataareavalue).format("yyyy-MM-dd");
    var ajaxurl = $("#DataApiAddress").val() + "api/analysis/" + getrealdataapitype + "/" + $("#BridgeId").val() + "/pointtype/" + pointtypeid + "/pointids/" + pointid + "/starttime/" + starttime + "/endtime/" + endtime;
    if (getrealdataapitype === "windandata") {
        var config = GetPointTypeAnalysisConfig(14);
        ajaxurl = config.DataApiAddress.trimEnd('/') + "/api/analysis/wind/detailanalysis/" + $("#BridgeId").val() + "/" + pointid + "/" + starttime + "/" + endtime;
    }
    $.ajax({
        url: ajaxurl,
        success: function (data) {
            debugger
            if (data.Code === 200 || data.code === 200) {
                if (pointtypename === "风速风向") {
                    var fsfxdata = data.result;
                    var datasHtmls = '<tr nowrap bgcolor="#CCCCFF"><th colspan="9" class="hdr">数据</th></tr>';
                    var head = '';
                    for (var h = 0; h < fsfxdata.speedGrade.length; h++) {
                        head += '<th class="freq">' + fsfxdata.speedGrade[h] + '</th>';
                    }
                    head = '<tr nowrap bgcolor="#CCCCFF">' + head + '<th class="freq">合计</th></tr>';
                    var content = '';
                    for (var w = 0; w < fsfxdata.windSpeedValues.length; w++) {
                        var cc = "";
                        for (var c = 0; c < fsfxdata.windSpeedValues[w].speedValues.length; c++) {
                            cc += '<td class="data">' + fsfxdata.windSpeedValues[w].speedValues[c].proportion + '</td>';
                        }
                        content += '<tr nowrap><td class="dir">' + fsfxdata.windSpeedValues[w].windKey + '</td>' + cc + '</tr>';
                    }
                    $('#pointdatastastics_chart_' + pointtypeid).parent().append('<div style="display:none"><table id = "freq" border = "0" cellspacing = "0" cellpadding = "0" ></table></div>');
                    $('#pointdatastastics_chart_' + pointtypeid).parent().find('#freq').html(datasHtmls + head + content);

                    Highcharts.chart('pointdatastastics_chart_' + pointtypeid, {
                        data: { table: 'freq', startRow: 1, endRow: 17, endColumn: 7 },
                        chart: { polar: true, type: 'column', backgroundColor: '#485B69' },
                        title: { text: '', enabled: false },
                        subtitle: { text: '' },
                        pane: { size: '80%' },
                        legend: { align: 'right', verticalAlign: 'top', y: 10, layout: 'vertical', itemStyle: { color: 'white' } },
                        xAxis: { categories: ['北', '北北东', '北东', '东北东', '东', '东南东', '南东', '南南东', '南', '南南西', '南西', '西南西', '西', '西北西', '北西', '北北西'], labels: { style: { color: 'white' } } },
                        yAxis: { min: 0, endOnTick: false, showLastLabel: true, title: { text: '风速占比 (%)' }, labels: { formatter: function () { return (this.value * 100).toFixed(2) + '%'; } }, reversedStacks: false },
                        tooltip: {
                            formatter: function () {
                                return '风向:<b>' + GetWindCn(this.point.name) + "</b><br/>风速:<b>" + this.series.name + '</b><br/>占比:<b>' + (this.point.y * 100).toFixed(2) + ' %</b><br/>';
                            }
                        },
                        plotOptions: { series: { stacking: 'normal', shadow: false, groupPadding: 0, pointPlacement: 'on' } },
                        exporting: { enabled: false }
                    });
                }
                else {
                    var unit = setChartInfo(pointtypename);
                    var timeFormatUnit = "yyyy-MM-dd hh:mm:ss";
                    var chartDataStr = data.Result.ResultDataJsons;
                    if (chartDataStr !== "") {
                        var chartData = ($.parseJSON(chartDataStr));
                        for (var i = 0; i < chartData.length; i++) {
                            chartData[i].showInLegend = false;
                        }
                        if (pointtypename === "水位") {
                            $("#pointdatastastics_chart_" + pointtypeid).highcharts({
                                chart: { type: 'areaspline', style: { fontFamily: "'Unica One', sans-serif" }, plotBorderColor: 'rgba(0,118,255,.8)', zoomType: 'x', backgroundColor: '#485B69' },
                                title: { text: null },
                                credits: { enabled: false },
                                exporting: { enabled: false },
                                subtitle: { text: '', style: { color: '#ffffff' } },
                                xAxis: { lineWidth: 0.5, lineColor: "#FFFFFF", tickWidth: 0.5, labels: { style: { color: '#FFFFFF', fontSize: '12px' } }, type: 'datetime', dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%m-%d', week: '%m-%d', month: '%Y-%m', year: '%Y' } }, labels: { style: { color: '#222' } },
                                yAxis: {
                                    gridLineWidth: 0,
                                    lineWidth: 0.5,
                                    lineColor: "#FFFFFF",
                                    tickWidth: 0.5,
                                    labels: { style: { color: '#FFFFFF', fontSize: '12px' } },
                                    title: { text: unit[0], style: { color: 'white' } },
                                    //plotLines: [
                                    //    { value: data.Result.RedWarning, width: 1, color: 'red', dashStyle: 'ShortDot', label: { text: '禁止通行:' + data.Result.RedWarning + unit[1], align: 'right', style: { color: 'red' } } },
                                    //    { value: data.Result.YellowWarning, width: 1, color: 'yellow', dashStyle: 'ShortDot', label: { text: '谨慎通行' + data.Result.YellowWarning + unit[1], align: 'right', style: { color: 'yellow' } } }
                                    //],
                                    max: data.Result.RedWarning + (Math.abs(data.Result.RedWarning) * 0.2),
                                    min: -1
                                },
                                plotOptions: { areaspline: { fillColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [[0, Highcharts.getOptions().colors[0]], [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]] }, marker: { enabled: false }, lineWidth: 1, states: { hover: { lineWidth: 1 } }, threshold: null } },
                                tooltip: { formatter: function () { var date = new Date(this.x); return "测点:[<b>" + this.series.name + "</b>]<br>时间:[" + date.format(timeFormatUnit) + "]<br>数据:[" + this.y + " " + unit[1] + "]"; } },
                                series: chartData
                            });
                        }
                        else if (pointtypename === "降雨量") {
                            var jlydata = [];
                            for (var j = 0; j < chartData[0].data.length; j++) {
                                var nkey = chartData[0].data[j][0];
                                var nvalue = chartData[0].data[j][1];
                                jlydata.push([nkey, (nvalue).toFixed(1) * 1]);
                            }

                            $("#pointdatastastics_chart_" + pointtypeid).highcharts({
                                chart: { type: 'column', style: { fontFamily: "'Unica One', sans-serif" }, plotBorderColor: '#606063', zoomType: 'x', backgroundColor: '#485B69' },
                                title: { text: null },
                                xAxis: { lineWidth: 0.5, lineColor: "#FFFFFF", tickWidth: 0.5, labels: { style: { color: '#FFFFFF', fontSize: '12px' } }, type: 'datetime', dateTimeLabelFormats: { millisecond: '%H:%M', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%m-%d', week: '%m-%d', month: '%Y-%m', year: '%Y' } }, labels: { style: { color: '#222' } },
                                yAxis: { gridLineWidth: 0, lineWidth: 0.5, lineColor: "#FFFFFF", tickWidth: 0.5, labels: { style: { color: '#FFFFFF', fontSize: '12px' } }, title: { text: unit[0], style: { color: 'white' } } },
                                legend: { enabled: false },
                                tooltip: { formatter: function () { var date = new Date(this.x); return "测点:[<b>" + $("#pointdatastastics_pointtype_24").find("option:selected").text() + "</b>]<br>时间:[" + date.format(timeFormatUnit) + "]<br>数据:[" + this.y + " " + unit[1] + "]"; } },
                                series: [{ data: jlydata, color: 'rgba(0,118,255,.8)' }], exporting: { enabled: false },
                                plotOptions: { column: { borderColor: "", shadow: false } }
                            });
                        }
                        else {
                            $("#pointdatastastics_chart_" + pointtypeid).highcharts({
                                chart: { type: 'spline', style: { fontFamily: "'Unica One', sans-serif" }, plotBorderColor: '#606063', zoomType: 'x', backgroundColor: '#485B69' },
                                title: { text: null },
                                credits: { enabled: false },
                                exporting: { enabled: false },
                                subtitle: { text: '', style: { color: '#ffffff' } },
                                xAxis: { lineWidth: 0.5, lineColor: "#FFFFFF", tickWidth: 0.5, labels: { style: { color: '#FFFFFF', fontSize: '12px' } }, type: 'datetime', dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%m-%d', week: '%m-%d', month: '%Y-%m', year: '%Y' } }, labels: { style: { color: '#222' } },
                                yAxis: { gridLineWidth: 0, lineWidth: 0.5, lineColor: "#FFFFFF", tickWidth: 0.5, labels: { style: { color: '#FFFFFF', fontSize: '12px' } }, title: { text: unit[0], style: { color: 'white' } } },
                                plotOptions: { spline: { lineWidth: 1.5, states: { hover: { lineWidth: 2.5 } }, marker: { enabled: false }, } },
                                tooltip: { formatter: function () { var date = new Date(this.x); return "测点:[<b>" + this.series.name + "</b>]<br>时间:[" + date.format(timeFormatUnit) + "]<br>数据:[" + this.y + " " + unit[1] + "]"; } },
                                series: chartData
                            });
                        }
                    } else {
                        $("#pointdatastastics_chart_" + pointtypeid).html("<label>未能成功加载" + pointtypename + "分析数据!</label>");
                    }
                }
            }
            else {
                $("#pointdatastastics_chart_" + pointtypeid).html("<label>未能成功加载" + pointtypename + "分析数据!</label>");
                return;
            }
        },
        error: function (msg) {
            $("#pointdatastastics_chart_" + pointtypeid).html("<label>未能成功加载" + pointtypename + "数据!</label>");
            console.log(msg);
        }
    });
}


function SaveModelSectionJsons() {
    $.post("/Setting/SaveEdit_SaveModelSection", { bridgeid: $("#BridgeId").val(), modelsectionjson: $("#ModelSections").val() }, function (data) {
        if (!data) {
            layer.msg("保存失败！");
        }
    });
};

function loadSection() {
    var $ModelSections = $("#ModelSections").val();
    var sectionData = $ModelSections ? JSON.parse($ModelSections) : [];
    var html = [];

    for (var i = 0; i < sectionData.length; i++) {
        html.push('<li class="sectionItme"><div class="checkbox"><a href="javascript:;" class="delSection icon-close" onclick="$.map3DMaker.delSection('
            + sectionData[i].id + ')"></a><label><input type="checkbox" class="checkboxVector" onclick="$.map3DMaker.showSection(' + sectionData[i].id + ',' + i + ')">'
            + sectionData[i].name + '</label></div></li>');
    };
    html.join('');
    $(".sectionMenu").html(html);
    if (html == "") {
        $(".sectionMenu").html('<span class="nodata">暂无断面数据</span>');
    }
}
function loadOrRemoveSection(data, i, type) {
    if (type == "load") {
        var html = '<li class="sectionItme"><div class="checkbox"><a href="javascript:;" class="delSection icon-close" onclick="$.map3DMaker.delSection('
            + data.id + ')"></a><label><input type="checkbox" class="checkboxVector" onclick="$.map3DMaker.showSection(' + data.id + ',' + i + ')">'
            + data.name + '</label></div></li>';
        $(".sectionMenu").append(html);
        $(".sectionMenu .nodata").remove();
    } else {
        $(".sectionMenu .sectionItme").eq(i).remove();
        if ($(".sectionMenu .sectionItme").length == 0) {
            $(".sectionMenu").html('<span class="nodata">暂无断面数据</span>');
        }
    }
};

function savePointMap() {
    var $ponitMapitem = $('.ponitMapitem');
    $ponitMapitem.removeClass('backgroundGray');
    var $ponitMapListArr = new Array();
    
    for (var i = 0; i < $ponitMapitem.length; i++) {
        var $ponitMapitemJson = {};
        $ponitMapitemJson.id = new Date().getTime();
        $ponitMapitemJson.name = $.trim($ponitMapitem.eq(i).find("input[name='imgName']").val());
        if ($ponitMapitem.eq(i).find('.pointSetWrapper').length == '') {
            layer.msg('未上传布点图！');
            $ponitMapitem.eq(i).addClass('backgroundGray');
            return;
        };
        $ponitMapitemJson.img = $ponitMapitem.eq(i).find('.pointSetWrapper').data('image');
        if ($ponitMapitemJson.name == "" || $ponitMapitemJson.img == "") {
            layer.msg('未填写布点图名称！');
            $ponitMapitem.eq(i).addClass('backgroundGray');
            return;
        };
        var $sensorPostions = $ponitMapitem.eq(i).find('.sensorPostion');
        var $sensorPostionArr = new Array();
        for (var j = 0; j < $sensorPostions.length; j++) {
            var $sensorPostion = $sensorPostions.eq(j).data('position');
            $sensorPostionArr.push($sensorPostion);
        };
        getbase64imgdata(i,$ponitMapListArr);
        $ponitMapitemJson.sensorMsg = $sensorPostionArr;
        $ponitMapListArr.push($ponitMapitemJson);
    };
    var loadingindex = layer.msg('上传图片数据中...', {
        icon: 16
        , shade: 0.01
    });

   
    window.entityTimer = setInterval(function () {
        try {
            for (var i = 0; i < $ponitMapListArr.length; i++) {
                if (!$ponitMapListArr[i].base64imgdata)throw{err: 'error'};
            };
            var udata = JSON.stringify($ponitMapListArr);
            $('#WindowPointSectionMapPositionEntitys').val(udata);
            clearInterval(window.entityTimer);
            $.post("/Setting/SaveWindowPointSectionMapPositionEntitys", { bridgeid: $("#BridgeId").val(), entityJsons: udata }, function (result) {
                layer.close(loadingindex);
                if (result) {
                    layer.msg("保存成功");
                    ShowWindowData_PointMapPositionOverview();
                    $('#sectionModal').modal('hide');
                    return;
                }
                layer.msg("保存失败");
            });
        }
        catch (err) {
            
        };
    }, 1000);
};

function getbase64imgdata(index,jsonArr) {
    html2canvas(document.querySelectorAll(".pointSetWrapper")[index]).then(canvas => {
        var base64imgdata = canvas.toDataURL("image/jpeg", 0.5);
        jsonArr[index].base64imgdata = base64imgdata;
    });
};
function SaveTimeLineEvent() {
    var newdata = {
        id: $("#timeline_Id").val(),
        hostId: $('#BridgeId').val(),
        startTime: $("#timeline_starttime").val(),
        endTime: $("#timeline_endtime").val(),
        group: $('#timeline_groupselect').val(),
        action: $('#timeline_actionselect').val(),
        filesjson: $('#eventuploadresult', parent.document).val()
    };
    if (newdata.group == "") {
        layer.msg('阶段信息未选择', { time: 2000 });
        return;
    }
    if (newdata.action == "") {
        layer.msg('操作信息未选择', { time: 2000 });
        return;
    }
    if (newdata.id === "") {
        $.post("/TimeEvent/Create", newdata, function (result) {
            var data = $.parseJSON(result);
            if (data != null) {
                layer.msg('事件信息已创建成功', { time: 2000 });
                timeLineItems.push(
                    {
                        id: data.Id,
                        content: '<span style="color:#97B0F8;" id="timeline_' + data.Id + '" data-itemjson=' + result + '>' + data.Text + '</span>',
                        group: data.Group,
                        start: data.StartTime,
                        end: data.EndTime,
                        type: 'box'
                    });
                timeline.setItems(timeLineItems);
                hideDialog();
            } else {
                layer.alert("添加事件失败!");
            }
        });
    } else {
        $.post("/TimeEvent/Update", newdata, function (result) {
            var data = $.parseJSON(result);
            if (data != null) {
                var order = 0;
                for (var i = 0; i < timeLineItems.length; i++) {//确定要删除的数组的索引位置
                    if (timeLineItems[i].id == data.Id) {
                        order = i;
                        break;
                    }
                }
                layer.msg('事件信息修改成功', { time: 2000 });
                timeLineItems[order].id = data.Id;
                timeLineItems[order].content = '<span style="color:#97B0F8;" id="timeline_' + data.Id + '" data-itemjson=' + result + '>' + data.Text + '</span>',
                    timeLineItems[order].group = data.Group;
                timeLineItems[order].start = data.StartTime;
                timeLineItems[order].end = data.EndTime;
                timeLineItems[order].type = 'box';
                timeline.setItems(timeLineItems);
                hideDialog();
            } else {
                layer.alert("添加事件失败!");
            }
        });
    }
}

function Edit_SetPointDeviceUnBanding(pointid, pointname, pointtypeid) {
    var olduuid = $("#point_edit_" + pointid).data("uuid");
    if (olduuid !== null && olduuid !== undefined && olduuid !== '') {
        layer.confirm('您确定解除【' + pointname + '】的设备绑定吗？设备编号【' + olduuid + '】',
            {
                btn: ['确定', '取消'], title: "设备解绑"
            },
            function () {
                if (pointid !== undefined && pointid !== "") {

                    $.post("/Setting/SetPointDeviceUnBanding", { bridgeid: $("#BridgeId").val(), pointid: pointid, uuid: olduuid },
                        function (result) {
                            if (result) {
                                layer.msg("解绑成功！");
                                $("#point_edit_" + pointid).data("uuid", '');
                                $("#set_pointli_" + pointid + " span ul .unbanding").hide();
                                hideDialog();
                            }
                            else {
                                layer.msg("解绑失败！");
                            }
                        });
                } else {
                    layer.msg("无法提交,硬件设备必选!");
                }
            });
    } else {
        layer.msg("该传感器未绑定！");
    }

}

function Edit_SetPointDeviceBanding(pointid, pointname, pointtypeid) {
    var olduuid = $("#point_edit_" + pointid).data("uuid");
    $("#devicebanding_pointid").data("pointid", pointid);
    $("#devicebanding_pointid").val(pointid);
    $("#devicebanding_pointname").val(pointname);
    var userName = $("#current_uName").val();
    $.post("/Setting/GetDevicePoints", { bridgeid: $("#BridgeId").val(), pointtypeid: pointtypeid, pointid: pointid, userName: userName }, function (result) {
        var datas = $.parseJSON(result);
        $("#devicebandingpointsTable").bootstrapTable('destroy');
        $("#devicebandingpointsTable").bootstrapTable({
            search: true,
            pagination: true,
            singleSelect: true,
            columns: [
                {
                    field: 'UUID',
                    formatter: function (value) {
                        return '<input type="radio" value="' + value + '" name="bandingdevice_group" data-uuid="' + value + '" ' + (olduuid == value ? "checked" : "") + ' style="width:30px;" onchange="ChangePointBandingDevice(this);"/>';
                    },
                    cellStyle: {
                        css: {
                            "width": "30px"
                        }
                    }
                },
                { title: '传感器类别', field: 'SensorNAME' },
                { title: '传感器名称', field: 'UUName' },
                {
                    title: '状态', field: 'STATUS',
                    formatter: function (value) {
                        return "<span title='" + value + "' class='pointstatus " + (value === "在线" ? "goodpoint" : "badpoint") + "'></span>";
                    }
                },
                { title: '绑定状态', field: 'BandingEdStatus' },
                { title: '设备厂商', field: 'BUID_COMPANY' },
                { title: '最新数据时间', field: 'TIME_RECENTLY' },
                {
                    title: '最新数据值',
                    field: 'VALUE_RECENTLY',
                    formatter: function (value) {
                        return "<input type='text' value='" + value + "' title='" + value + "' style='width:150px;' disabled='disabled'/>";
                    }
                }
            ],
            data: datas
        });
    });
    if (olduuid == "") {
        $(".pointdevicebangingedstatu").hide();
    }
    else {
        $(".pointdevicebangingedstatu").show();
    }
    showDialog(900, "Model_SetPointDeviceBandingWindow");
}

function ChangePointBandingDevice(obj) {
    console.log($(obj).data("uuid"));
}
function SetPointDeviceBanding() {
    var newuuid = $("input[name='bandingdevice_group']:checked").val();
    if (newuuid == null || newuuid == "") {
        layer.msg("请选择需要绑定的硬件设备!");
        return;
    }
    var pointid = $("#devicebanding_pointid").val();
    if (pointid != undefined && pointid != "") {
        $.post("/Setting/SetPointDeviceBanding", { bridgeid: $("#BridgeId").val(), pointid: pointid, uuid: newuuid },
            function (result) {
                if (result) {
                    //var oldpointId = result;
                    layer.msg("绑定成功");
                    //$("#point_edit_" + oldpointId).data("uuid", '');
                    //$("#set_pointli_" + oldpointId + " span ul .unbanding").hide();
                    $("#point_edit_" + pointid).data("uuid", newuuid);
                    $("#set_pointli_" + pointid + " span ul .unbanding").show();
                    hideDialog();
                }
                else {
                    layer.msg("绑定失败");
                }
            });
    } else {
        layer.msg("无法提交,硬件设备必选!");
    }
}
function SaveDepartmentAuthorizesInfo() {
    //数据权限
    var depid = $("#tablelisttitle").data("depid");
    var treeNodes = $.fn.zTree.getZTreeObj("departmentauthorizestree").getCheckedNodes(true);
    var checkedNodeIds = "";
    for (var i = 0; i < treeNodes.length; i++) {
        checkedNodeIds += treeNodes[i].xid + ",";
    }
    $.post("/Department/SaveDepartmentAuthorizesInfo", { departmentid: depid, nodeids: checkedNodeIds }, function (result) {
        if (result === "True" || result === "true") {
            loaddinghide();
            layer.msg("已保存成功！");
            hideDialog("Model_SetDepartmentAuthorizes_Window");
            hideDialog();
        } else {
            layer.alert("错误:" + result, { title: "错误提示" });
            loaddinghide();
        }
    });
}

function Edit_SetPointPosition(pointid) {
    if ($("#ModelShowType").data("showedtype") == "three3d") {
        if ($('#addPointAction').find('span').hasClass('actived')) {
            $('#addPointAction').find('span').trigger('click');
        }
        $.map3DMaker.closeAddPointEvent();
        $.map3DMaker.editPointByPointId(pointid);
    } else {
        Edit_AddPointFromPointType(pointid);
    }
}
function SaveAddPoint_Window() {
    var pointid = $.trim($("#addpointid").val()) * 1;
    var arr = new Array();
    $("input[name='addpoint_selecttype']:checked").each(function (i) {
        arr[i] = $(this).val();
    });
    var typeids = arr.join(",");
    if (typeids.length == 0) {
        layer.msg("监测类型未选择");
        return;
    }
    var pointname = $.trim($("#addpointname").val());
    var instalremarkame = $.trim($("#addpointinstalremark").val());
    if (pointname === "") {
        layer.msg("传感器名称未输入");
        return;
    }
    $.post("/Setting/SaveEdit_AddBridgePoint_Model",
        {
            bridgeid: $("#BridgeId").val(),
            pointid: pointid,
            typeid: typeids,
            pointname: pointname,
            position: "",
            instalRemark: instalremarkame
        },
        function (result) {
            if (result.split(',')[0] === "添加失败") {
                layer.msg(result);
                return;
            }
            var point = $.parseJSON(result);
            var types = typeids.split(',');
            for (var i = 0; i < types.length; i++) {
                var li = '<li id="set_pointli_' + point.Id + '" class="set_pointli_' + point.Id + ' badpoint device_' + types[i] + '_' + point.Id + '">' +
                    '<input id="point_edit_' + point.Id + '" type="hidden" class="menu_sec_name" disabled="disabled" value="' + point.ShowText + '"  data-pointtypeid="' + types[i] + '" data-pointid="' + point.Id + '" data-maxvalue="" data-minvalue="" data-instalremark="' + instalremarkame + '" data-uuid="' + point.UUID + '"/>' +
                    '<span class="state" data-pointstatus=""></span>' +
                    '<input id="point_updatenametext_' + point.Id + '" value="' + point.ShowText + '" class="updatepointnameshowtext dsp" onblur="SaveEditPointName(this)" maxlength="16">' +
                    '<span class="dropdown fr pointsetmenu">' + '<i class="ico ico-sideBar-more dropdown-toggle" data-toggle="dropdown" onclick="toggleDropdown(this);cancelBubble()"></i >' +
                    '<ul class="dropdown-menu scroll">' +
                    '<li><a href="javascript:void(0);" onclick="Edit_UpdatePointName(this);">重命名</a></li>' +
                    '<li><a href="javascript:void(0);" onclick="Edit_SetPointPosition(' + point.Id + ');">调点/修改</a></li>' +
                    '<li><a href="javascript:void(0);" onclick="Edit_SetPointDeviceBanding(' + point.Id + ',\'' + point.ShowText + '\',' + types[i] + ');">设备绑定</a></li>' +
                    '<li id="li_pointubind" class="unbanding ' + (point.UUID == null || point.UUID == undefined || point.UUID == '' ? "dsp" : "") + '"><a href="javascript:void(0);" onclick="Edit_SetPointDeviceUnBanding(' + point.Id + ',\'' + point.ShowText + '\',' + types[i] + ');">设备解绑</a></li>' +
                    '<li class="' + (types[i] * 1 === PointTypeEnum.Video ? "dsp" : "") + '"><a href="javascript:void(0);" onclick="Edit_SetMonitorPointValue(' + point.Id + ');">监测值</a></li>' +
                    '<li><a href="javascript:void(0);" onclick="DeleteBridgePoint(' + types[i] + ',' + point.Id + ');">删除</a></li>' +
                    '</ul>' +
                    '</span >' +
                    '<a href="javascript:;" title="拖动点到模型上" class="fr movePonit"></a>' +
                    '<span class="showtext" onclick="ShowNowTimePointData(' + point.Id + ',' + types[i] + ')">' + point.ShowText + '</span>' +
                    '</li>';
                $('#setpointtypepanel_' + types[i]).find("div ul").eq(1).append(li);
                var pnum = $('#setpointtypepanel_' + types[i] + ' div a .num').text().split('/')[1] * 1 + 1;
                $('#setpointtypepanel_' + types[i] + ' div a .num').text("0/" + pnum);
            }
            if ($("#ModelShowType").data("showedtype") === "mapmodel") {
                mapAddPointMarker(point);
            }
            hideDialog("Model_AddPoint_Window");
            layer.msg("添加成功");
        });
}
function SaveEditPoint_Window() {
    var pointid = $.trim($("#editbasepointid").val()) * 1;
    var pointname = $.trim($("#editbasepointname").val());
    var instalremark = $.trim($("#editbasepointinstalremark").val());
    var pointposition = $.trim($("#editbasepointposition").data("value"));
    var group = $.trim($("#editbasepointgroup").val());
    $.post("/Setting/SaveEdit_SaveBridgePoint_Model",
        {
            bridgeid: $("#BridgeId").val(),
            pointid: pointid,
            pointname: pointname,
            position: pointposition,
            groupName: group,
            instalRemark: instalremark
        }, function (result) {
            if (result.split(',')[0] == "修改失败") {
                layer.msg(result);
                return;
            }
            var newpoint = $.parseJSON(result);
            for (var i = 0; i < newpoint.PointType.length; i++) {
                if (newpoint.PointType[i] != "") {
                    var li = $('#setpointtypepanel_' + newpoint.PointType[i]).find('#panel' + newpoint.PointType[i]).find('#set_pointli_' + newpoint.Id);
                    $(li).find(".menu_sec_name").data("instalremark", newpoint.InstalRemark);
                    $(li).find(".menu_sec_name").val(newpoint.Name);
                    $(li).find(".showtext").text(newpoint.Name);
                    $(li).find("#point_updatenametext_" + newpoint.Id).val(newpoint.Name);
                }
            }
            $("#addpointname").removeAttr("disabled");
            layer.msg("修改成功");
        }
    );
}

function SetChartRefreshImgStyle(obj) {
    if ($(obj).data("deg") == null) {
        $(obj).data("deg", "0");
    }
    var deg = $(obj).data("deg") * 1;
    deg += 360;
    if (deg > 99999) {
        deg = 0;
    }
    $(obj).data("deg", deg);
    $(obj).css({ "transform": "rotate(" + deg + "deg)" });
}

function SaveRealDataWindowSetting(obj) {
    var thistype = $(obj).val();
    var realtype_array = new Array();
    $('input[name="realdatawindowrealtype"]:checked').each(function () {
        realtype_array.push($(this).val());
    });
    var realtype_arraystr = realtype_array.join(',');
    $.post("/Setting/SaveRealDataWindowSetting", { bridgeid: $("#BridgeId").val(), typestr: realtype_arraystr }, function (result) {
        if (!result) {
            layer.msg("实时数据分类保存失败");
        } else {
            layer.msg("实时数据分类保存成功");
            //是否隐藏
            if (contains(realtype_array, thistype)) {
                //显示
                $(".realtype_" + thistype).show();
                $(".realtype_" + thistype).trigger('click');
            } else {
                //隐藏
                $(".realtype_" + thistype).hide();
                $(".bottomRealPoints span:visible").eq(0).trigger('click');
            }
            //是否一个都没有
            if (realtype_array.length == 0) {
                $("#HomeRealDataAllStasticsBody").html("");
            }
        }
    });
}
function ShowModelReLiTu(obj) {
    if ($(obj).hasClass("active")) {
        $.map3DMaker.hideReLiTu('wendu');
    }
    else {
        $.map3DMaker.showReLiTu('wendu');
    }
}
function ShowMonitorInfoCard(obj) {
    if (obj == undefined)
        obj = $(".showWay .way .projectInfo");

    if ($(obj).data("isload") == undefined || $(obj).data("isload") == false) {
        var url = $("#DataApiAddress").val() + "api/bridges/getbridgebaseinfo/" + $("#BridgeId").val();
        $.get(url, function (result) {
            if (result.Code === 200) {
                $(".projectInfoContainer .infoTop img").attr("src", result.Result.BaseInfo.Photo);
                $(".projectInfoContainer .infoTop img").attr("alt", $("#BridgeName").val());
                $(".projectInfoContainer .infoTop .projectName").text($("#BridgeName").val());
                $(".projectInfoContainer .infoTop .projectName").attr("title", $("#BridgeName").val());
                $(".projectInfoContainer .infoTop .base_remark").val(result.Result.BaseInfo.Summary);
                $(".projectInfoContainer .infoTop .base_positionremark").text(result.Result.BaseInfo.PositionRemark);
                $(".projectInfoContainer .infoBottom .base_slopetype").text(result.Result.SlopeTypeEnum[result.Result.BaseInfo.SlopeType]);
                $(".projectInfoContainer .infoBottom .base_dizhi").text(result.Result.BaseInfo.DiZhi);
                $(".projectInfoContainer .infoBottom .base_jiegou").text(result.Result.BaseInfo.JieGou);
                $(".projectInfoContainer .infoBottom .base_mianji").text(result.Result.BaseInfo.MianJi + " (平方公里)");
                $(".projectInfoContainer .infoBottom .base_monitorabsoluteheight").text(result.Result.BaseInfo.MonitorAbsoluteHeight);
                $(".projectInfoContainer .infoBottom .base_bagao").text(result.Result.BaseInfo.BaGao);
                $(obj).data("isload", true);
            }
        });
    }
}
function Edit_Overview_Video_Window() {
    $.post("/Setting/GetVideoNotBandingPoint", { monitorObjectId: $("#BridgeId").val() }, function (result) {
        $("#VideoId").val(0);
        $("#VideoTitle").val("");
        var points = $.parseJSON(result);
        var notbangdingpointhtmls = '';
        for (var i = 0; i < points.length; i++) {
            notbangdingpointhtmls += '<option value="' + points[i].Id + '" data-uuid="' + points[i].UUID + '">' + points[i].ShowText + '</option>';
        }
        $("#VideoPointId").html(notbangdingpointhtmls);
        GetVideoUrlForPointId();
        showDialog(500, 'Model_Overview_Video_Window');
    });
}
function EditVideoStasticsDetail(id) {
    $.post("/Setting/GetVideoNotBandingPoint", { monitorObjectId: $("#BridgeId").val() }, function (result) {
        var points = $.parseJSON(result);
        var notbangdingpointhtmls = '';
        for (var i = 0; i < points.length; i++) {
            notbangdingpointhtmls += '<option value="' + points[i].Id + '" data-uuid="' + points[i].UUID + '">' + points[i].ShowText + '</option>';
        }
        $("#VideoPointId").html(notbangdingpointhtmls);
        $("#VideoId").val(id);
        $("#VideoTitle").val($("#realvideo_" + id).data("title"));
        $("#VideoUrl").val($("#realvideo_" + id).data("videourl"));
        $("#VideoPointId").val($("#realvideo_" + id).data("pointid"));
        showDialog(500, 'Model_Overview_Video_Window');
    });
}
function DeleteVideoStasticsDetail(id) {
    layer.confirm('确认删除该视频监控？', function () {
        $.post("/Setting/SaveEdit_DeleteVideoStastics", { monitorobjectid: $("#BridgeId").val(), id: id }, function (reuslt) {
            if (reuslt) {
                layer.msg('删除成功');
                $("#videoItem_" + id).remove();
            }
            else {
                layer.msg('删除失败');
            }
        });
    });
}

function GetVideoUrlForPointId() {
    var pointid = $("#VideoPointId").val();
    if (pointid == undefined || pointid === "") {
        return;
    }
    $(".VideoUrl").text("");
    $(".loadingvideourl").show();
    //请求硬件平台获取视频地址
    var uuid = $('#VideoPointId option:selected').data("uuid");
    $.post($("#HardwareAeroiotAppAddress").val() + "api/device/videodeviceaddress", { uuid: uuid }, function (result) {
        if (result.code === 200 && JSON.stringify(result.result) !== "{}") {
            $("#VideoUrl").val(result.result[uuid]);
        } else {
            layer.msg("未能成功获取视频URL，请稍后再试");
        }
        $(".loadingvideourl").hide();
    });
}
function SaveVideoStasticsDetail() {
    var id = $("#VideoId").val();
    var title = $.trim($("#VideoTitle").val());
    var pointid = $.trim($("#VideoPointId").val());
    var url = $.trim($("#VideoUrl").val());
    var uuid = $('#VideoPointId option:selected').data("uuid");
    if (title === "" || pointid === "" || uuid === "") {
        layer.alert("信息填写不完整,无法保存");
        return;
    }
    var data = {
        monitorobjectid: $("#BridgeId").val(),
        id: id,
        title: title,
        pointid: pointid,
        uuid: uuid,
        url: url
    };
    $.post("/Setting/EditVideoStasticsDetail", data, function (result) {

        if (result !== "") {
            var data = $.parseJSON(result);
            console.log(data);
            if (id != 0) {
                $("#realvideo_" + id).data("title", title);
                $("#realvideo_" + id).data("videourl", url);
                $("#realvideo_" + id).data("uuid", data.Uuid);
                $("#realvideo_" + id).data("pointid", data.PointId);
                $("#realvideo_" + id).data("order", data.OrderNum);

                hideDialog();
                LoadingVideoDetail(id, uuid);
                layer.msg("保存成功");
            }
            else {
                id = data.Id;
                var newhtml = '<li class="videoItem reveal_drag videoshow2" id="videoItem_' + data.Id + '">' +
                    '<div id="realvideo_' + data.Id + '" class="video-js vjs-default-skin" style="width:100%;height:100%;object-fit:cover" data-uuid="' + uuid + '" data-id="' + data.Id + '" data-title="' + data.Title + '" data-pointid="' + data.PointId + '" data-order="' + data.Order + '" data-videourl="' + data.VideoUrl + '"></div>' +
                    '<i class="ico ico-drag editable"></i>' +
                    '<div class="videoText">' +
                    '<span class="videoState stateDranger"></span>' +
                    '<span class="videoName">' + data.Title + '</span>' +
                    '</div>' +
                    '<span class="moreMenu editable dropdown">' +
                    '<i class="ico ico-sideBar-more dropdown-toggle" data-toggle="dropdown"></i>' +
                    '<ul class="dropdown-menu scroll">' +
                    '<li><a href="javascript:void(0);" onclick="EditVideoStasticsDetail(' + data.Id + ');">编辑</a></li>' +
                    '<li><a href="javascript:void(0);" onclick="DeleteVideoStasticsDetail(' + data.Id + ');">删除</a></li>' +
                    '</ul>' +
                    '</span>' +
                    '</li>';
                $("#videostasticscontent .videoList:first").append(newhtml);

                //重新绑定复制拖拽
                $('.video_drag_box li').arrangeable({
                    dragSelector: '.ico-drag', myDragEnd: function (data) {
                        SaveVideoOverviewOrderNum();
                    }
                });

                hideDialog();
                layer.msg("保存成功");

                LoadingVideoDetail(id, uuid);
            }
        }
        else {
            layer.msg("保存失败");
        }
    });
}

function LoadingVideoDetail(id, uuid) {

    var vurl = $("#realvideo_" + id).data("videourl"), title = $("#realvideo_" + id).data("title");
    if (vurl == undefined || vurl === "") {
        layer.msg("《" + title + "》视频配置参数错误，无法播放视频");
        return;
    }
    console.log("播放视频：" + vurl);
    if (vurl.indexOf('http') != -1) {
        try {
            var player = window.player = videojs('realvideo_' + id,
                {
                    techOrder: ['flvjs'],
                    languages: { 'zh-CN': { 'Retry': '重试' } },
                    sources: [{ src: vurl, type: 'video/x-flv' }],
                    flvjs: { mediaDataSource: { isLive: true, cors: true, withCredentials: false } },
                    preload: 'auto',
                    playbackRates: [0.5, 1, 1.5, 2],
                    controls: true,
                    autoplay: true,
                    notSupportedMessage: '暂不支持播放该媒体',
                    controlBar: { volumePanel: { inline: false } }
                }, function () {
                    var sysDeviceCode = getQueryVariable(vurl, 'stream');
                    var command = "move";
                    $('#realvideo_' + id).append(
                        `<div class="video-control">
                        <div class="video-control-btns">
                            <button class="video-control-btn control-up" onclick="videoControl(this);" data-param="{sys_device_code: ${sysDeviceCode},command: ${command} paras: [{ direction: 2 }]}"></button>
                            <div class="video-control-middle clearfix">
                                <button class="video-control-btn control-left" onclick="videoControl(this);" data-param="{sys_device_code: ${sysDeviceCode},command: ${command} paras: [{ direction: 0}]}"></button>
                                <div class="video-control-scale">
                                    <button class="video-control-btnscale control-enlarge" onclick="videoControl(this);" data-param="{sys_device_code: ${sysDeviceCode},command: ${command} paras: [{ direction: 5}]}"></button>
                                    <button class="video-control-btnscale control-narrow" onclick="videoControl(this);" data-param="{sys_device_code: ${sysDeviceCode},command: ${command} paras: [{ direction: 4}]}"></button>
                                </div>
                                <button class="video-control-btn control-right" onclick="videoControl(this);" data-param="{sys_device_code: ${sysDeviceCode},command: ${command} paras: [{ direction: 1}]}"></button>
                            </div>
                            <button class="video-control-btn control-down" onclick="videoControl(this);" data-param="{sys_device_code: ${sysDeviceCode},command: ${command} paras: [{ direction: 3}]}"></button>
                        </div>
                    </div>
                    <div class="video-control-loading">
                            镜头切换中，请稍后... 
                    </div>`);
                    this.play();
                });
        } catch (e) {
            console.log("播放视频出现错误：" + e);
        }
    } else {
        $.post($("#HardwareAeroiotAppAddress").val().trimEnd('/') + "/api/device/videodeviceaddress", { uuid: uuid }, function (result) {

            if (result.code === 200 && JSON.stringify(result.result) !== "{}") {
                var vurl = result.result[uuid];

                console.log(vurl);
                if (vurl === "") {
                    layer.msg("获取视频数据成功，但解析视频URL为空");
                } else {
                    var appKey = result.result["appKey"];
                    var appSecret = result.result["appSecret"];
                    var formData = new FormData();
                    formData.append('appKey', appKey);
                    formData.append('appSecret', appSecret);

                    axios.post("https://open.ys7.com/api/lapp/token/get", formData).then(function (reponse) {
                            var data = reponse.data
                            if (data.code == 200) {
                                var accessToken = data.data.accessToken;
                                formData = new FormData();
                                formData.append('accessToken', accessToken);
                                formData.append('deviceSerial', vurl);
                                formData.append('channelNo', 1);
                                axios.post("https://open.ys7.com/api/lapp/live/address/limited", formData )
                                    .then(function (reponse) {
                                        var data = reponse.data;
                                        if (data.code == 200) {
                                            var liveAddress = data.data.flvAddress;
                                            var dp = new DPlayer({
                                                container: document.getElementById('realvideo_' + id),
                                                live: true,
                                                autoplay: true,
                                                video: {
                                                    url: 'demo.flv',
                                                    type: 'customFlv',
                                                    customType: {
                                                        customFlv: function (video, player) {
                                                            const flvPlayer = flvjs.createPlayer({
                                                                type: 'flv',
                                                                url: liveAddress,
                                                            });
                                                            flvPlayer.attachMediaElement(video);
                                                            flvPlayer.load();
                                                        },
                                                    },
                                                },
                                            });

                                        }
                                    })
                                    .catch(function (error) {
                                        console.log(error);
                                    });
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                        });

                }
            } else {
                layer.msg("未能成功获取视频URL，请稍后再试");
            }
        })

    }
}
function videoControl(dom) {
    $(dom).parents('.video-js').addClass('video-controlIng');
    var params = $(dom).data("param");
    console.log(params);
    $.ajax({
        url: 'http://39.129.24.34:48080/device/control', //请求的url地址
        dataType: "json", //返回格式为json
        async: true,//请求是否异步，默认为异步，这也是ajax重要特性
        cache: false,
        'contentType': "application/json",
        'processData': false,
        'data': params, //参数值
        'type': "POST", //请求方式
        headers: {
            //     'Content-Type':'application/json',
            //     'sys_id':'1333333333',
            //     'token':'1333333333',
            //     "Authorization":"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJrZW4iLCJpYXQiOjE1Mzc1NTQzMDksImRhdGEiOnsidXNlcm5hbWUiOiJ4dXRvbmdiYW8iLCJpc19zdXBlcnVzZXIiOjEsImlkIjoxNywibG9naW5fdGltZSI6MTUzNzU1NDMwOX0sImV4cCI6MTUzODE1NDMwOX0.32Lys4hjjY2XRpM2r9YSmpYA798u821m_M5Tzb6wxIU",
        },
        beforeSend: function (xhr) {
            //请求前的处理
            // xhr.setRequestHeader("sys_id:'1333333333'");
            // xhr.setRequestHeader("token:'1333333333'");
        },
        success: function (req) {
            //请求成功时处理
        },
        complete: function () {
            //请求完成的处理
            $(dom).parents('.video-js').removeClass('video-controlIng');
        },
        error: function (e) {
            //请求出错处理
            $(dom).parents('.video-js').removeClass('video-controlIng');
            console.log(e.statusText)
        }
    });
}
//获取url的参数
function getQueryVariable(url, variable) {
    const query = url.substring(1);
    const vars = query.split("&");
    for (let i in vars) {
        const pair = vars[i].split("=");
        if (pair[0] == variable) { return pair[1]; }
    }
    return (false);
}

function ShowWindowData_VideoStastics_Module() {
    if ($("#overviewwindowli_7").css("display") != undefined && $("#overviewwindowli_7").css("display") != "none") {
        var config = GetPointTypeAnalysisConfig(33);
        $.get(config.DataApiAddress + "/view/analysis/video/righthistory/monitorobjectid/" + $("#BridgeId").val(), function (result) {
            $("#overviewwindowli_7").html(result);
        });
    }
}
function ShowWindowData_VideoStastics() {
    if ($("#overviewwindowli_7").css("display") != undefined && $("#overviewwindowli_7").css("display") != "none") {
        var allvideolis = $("#overviewwindowli_7 #videoList").find(".videoItem");
        for (var i = 0; i < allvideolis.length; i++) {
            LoadingVideoDetail($(allvideolis[i]).find(".video-js").data("id"), $(allvideolis[i]).find(".video-js").data("uuid"));
        }
    }
}

function cancelBubble(e) {
    if (e && e.stopPropagation) {
        e.stopPropagation();
    } else {
        window.event.cancelBubble = true;
    }
}

var toggleDropdownObj = null;
function toggleDropdown(obj) {
    var parent = $(obj).parent();
    if (toggleDropdownObj) {
        if (parent.hasClass("open")) {
            parent.removeClass("open");
            toggleDropdownObj = null;
        } else {
            toggleDropdownObj.removeClass("open");
            parent.addClass("open");
            toggleDropdownObj = parent;
        }

    } else {
        parent.addClass("open");
        toggleDropdownObj = parent;
    };
}

function Set_RightVideoShowWindowType(showtype) {
    if (showtype === 2) {
        $("#videostasticscontent .videoItem").removeClass("videoshow1").addClass("videoshow2");
    }
    else if (showtype === 1) {
        $("#videostasticscontent .videoItem").removeClass("videoshow2").addClass("videoshow1");
    }

    $.post("/Setting/SaveEdit_SetVideoShowType", { monitorobjectid: $("#BridgeId").val(), showtype: showtype }, function (result) {
        if (result) {
            layer.msg("保存成功");
        }
    });
}
function EditFeatureMenuText() {
    showDialog(450, "Model_RightFeatue_Window");
}

function SaveWindowRightFeature() {
    var groups = "";
    $("input[name='rightfeaturecheck']:checkbox").each(function () {
        if ($(this).is(':checked')) {
            groups += $(this).data('id') + ',';
        }
    });
    if (groups.indexOf("survey") <= -1 || groups == ",") {
        layer.alert("概况面板不能取消");
        return;
    }
    $.post("/Setting/SaveWindowRightFeature", { monitorobjectid: $("#BridgeId").val(), showfeatures: groups }, function (result) {
        if (result.toLowerCase() === "true") {
            layer.msg("保存成功");
            hideDialog("Model_RightFeatue_Window");
            $(".mainFloatR .tab-tit .tab-item").hide();
            var shows = groups.split(',');
            for (var i = 0; i < shows.length; i++) {
                if (shows[i] !== "") {
                    $(".mainFloatR .tab-tit .tab_" + shows[i]).show();
                }
            }
        } else {
            layer.msg("保存失败");
        }
    });
}

function ShowPointTypeOverviewsPoints(obj) {
    if ($(obj).parent().find(".typeoverviewspoints").html() == "") {
        var sobj = $(obj).parent().find(".typeoverviewspoints");
        var htmls = "";
        var valuedatas = $(obj).parent().parent().find(".overviewvalue").data("overviewpointsvalue");
        var maxv = null;
        for (var i = 0; i < valuedatas.length; i++) {
            var nv = valuedatas[i].Value;
            if (nv != null && maxv == null) {
                maxv = nv * 1;
            }
            else if (nv != null && (nv * 1) >= maxv) {
                maxv = nv * 1;
            }
        }
        var statisticstype = $(obj).parent().parent().find(".overviewvalue").data("statisticstype");
        var maxcontent = "";
        for (var j = 0; j < valuedatas.length; j++) {
            var key = valuedatas[j].PointId;
            var name = valuedatas[j].PointShowText;
            var typeid = valuedatas[j].PointType;
            var v = valuedatas[j].Value;
            var u = valuedatas[j].Unit;
            var stype = "";
            if (statisticstype == 0) { stype = "平均值"; }
            else if (statisticstype == 1) { stype = "最大值"; }
            else if (statisticstype == 2) { stype = "最小值"; }
            else if (statisticstype == 3) { stype = "合计"; }

            var showtext = name + " " + stype + ":" + v + u;
            if (maxv == v)
                maxcontent = '<li class="thiskey"><span title="最大值传感器"></span><a title="' + showtext + '" href="javascript:void(0)" onclick="ShowNowTimePointData(' + key + ',' + typeid + ')">' + name + '</a></li>';
            else
                htmls += '<li><a title="' + showtext + '" href="javascript:void(0)" onclick="ShowNowTimePointData(' + key + ',' + typeid + ')">' + name + '</a></li>';
        }
        $(obj).parent().find(".typeoverviewspoints").html("<ul>" + maxcontent + htmls + '</ul>');
        $(sobj).show();
    }
}
function Save_PointTypeStasticsShowTimes(typeid, typename) {
    $.post("/Setting/GetPointTypeStasticsCategory", { monitorobjectid: $("#BridgeId").val(), typeid: typeid }, function (result) {
        var datas = $.parseJSON(result);
        $("#Model_PointTypeStastics_TimesCategory_Window .conent").html("");
        var timeHtmls = '';
        for (var i = 0; i < datas.length; i++) {
            var npc = '';
            for (var j = 0; j < datas[i].Items.length; j++) {
                npc += '<label><input name="stastics_pointtype_' + datas[i].Category + '" type="checkbox" value="' + datas[i].Items[j].ShowMinute + '" ' + (datas[i].Items[j].IsShow ? "checked" : "") + ' />' + datas[i].Items[j].CategoryName + '</label>';
            }
            timeHtmls += '<label for="name" class="name">' + datas[i].Category + '间隔设置</label><ul class="form-inline pointtypestasticsgroup group_' + datas[i].Category + '" data-category=' + datas[i].Category + '><li class="mt10 timespcshow">' + npc + '</li></ul>';
        }
        $("#Model_PointTypeStastics_TimesCategory_Window .modal-title").html("【" + typename + "】分类统计时间间隔设置");
        $("#Model_PointTypeStastics_TimesCategory_Window .setpointtypestasticscategory_pointtypeid").val(typeid);
        $("#Model_PointTypeStastics_TimesCategory_Window .conent").html(timeHtmls);
        showDialog(250, "Model_PointTypeStastics_TimesCategory_Window", 1041);
    });
}
function SavePointTypeStastics_TimesCategory_Window(obj) {
    $(obj).attr("disabled", "disabled");
    var pointtypestasticsgroup = $("#Model_PointTypeStastics_TimesCategory_Window .pointtypestasticsgroup");
    var setdatas = new Array();
    for (var i = 0; i < pointtypestasticsgroup.length; i++) {
        var category = $(pointtypestasticsgroup[i]).data("category");
        var nowCategoryMinutes = new Array();
        $("input[name='stastics_pointtype_" + category + "']:checked").each(function (index, item) {
            if ($("input[name='stastics_pointtype_" + category + "']:checked").length - 1 === index) {
                nowCategoryMinutes.push($(this).val());
            } else {
                nowCategoryMinutes.push($(this).val());
            }
        });
        if (nowCategoryMinutes.length == 0) {
            layer.alert(category + "间隔设置不正确,请务必选择一项");
            $(obj).removeAttr("disabled");
            return;
        }
        var ndata = new Object();
        ndata.name = category;
        ndata.items = nowCategoryMinutes;
        setdatas.push(ndata);
    }

    var postdata = {
        monitorobjectid: $("#BridgeId").val(),
        typeid: $("#Model_PointTypeStastics_TimesCategory_Window .setpointtypestasticscategory_pointtypeid").val() * 1,
        showminutedatas: JSON.stringify(setdatas)
    };
    loaddingshow();
    $.post("/Setting/SetPointTypeStasticsCategory", postdata, function (result) {
        loaddinghide();
        if (result.toLowerCase() === "true") {
            layer.msg("保存成功");
            hideDialog();
        }
        else {
            layer.alert("保存失败");
        }
        $(obj).removeAttr("disabled");
    });
}
